我想使用Mantle
将某些对象序列化为此JSON
:
{
"name": "John Smith",
"age": 30,
"department_id":123
}
我有两个班级员工:
#import <Mantle/Mantle.h>
@interface Department : MTLModel <MTLJSONSerializing>
@property(nonatomic)int id;
@property(nonatomic)NSString *name;
@end
和Employee类:
#import <Mantle/Mantle.h>
#import "Department.h"
@interface Employee : MTLModel <MTLJSONSerializing>
@property(nonatomic)NSString *name;
@property(nonatomic)int age;
@property(nonatomic)Department *department;
@end
@implementation Employee
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name":@"name",
@"age":@"age",
@"department.id":@"department_id"
};
}
@end
在序列化Employee实例时,我收到以下内容 异常:“NSInternalInconsistencyException”,“department.id不是 员工的财产。“
这里有什么问题?有没有办法将对象序列化为单个字典,而不是将department对象嵌套在employee对象中?
答案 0 :(得分:0)
首先从Employee.m文件中删除此代码
@implementation Employee
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name":@"name",
@"age":@"age",
@"department.id":@"department_id"
};
}
然后,只要您想要serialize
Employee
对象
Employee *objEmployee = [Employee instanceFromDict:responseObject];
我希望它对你有用。一切顺利!!
答案 1 :(得分:0)
好的,我从这里得到了它: Mantle property class based on another property?
我将映射字典修改为像这样
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name":@"name",
@"age":@"age",
NSStringFromSelector(@selector(department)) : @[@"department_id"]
};
}
并补充说:
+ (NSValueTransformer *)departmentJSONTransformer {
return [MTLValueTransformer transformerUsingReversibleBlock:^id(Department *department, BOOL *success, NSError *__autoreleasing *error) {
return [MTLJSONAdapter JSONDictionaryFromModel:department error:nil];
}];
}