[英]Mantle Objective C: mapping nested properties to JSON
I want to use Mantle
to serialize some objects to this JSON
: 我想使用Mantle
将一些对象序列化为JSON
:
{
"name": "John Smith",
"age": 30,
"department_id":123
}
I have two classes Department Employee: 我有两类部门员工:
#import <Mantle/Mantle.h>
@interface Department : MTLModel <MTLJSONSerializing>
@property(nonatomic)int id;
@property(nonatomic)NSString *name;
@end
and the Employee class: 和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
when serializing an Employee instance I receive the following exception: "NSInternalInconsistencyException", "department.id is not a property of Employee." 序列化Employee实例时,我收到以下异常:“ NSInternalInconsistencyException”,“ department.id不是Employee的属性”。
What's wrong here? 怎么了 is there a way to serialize the object as as a single dictionary instead of nesting the department object inside the employee object? 有没有一种方法可以将对象序列化为单个字典,而不是将部门对象嵌套在员工对象内部?
first remove this code from your Employee.m file 首先从您的Employee.m文件中删除此代码
@implementation Employee
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name":@"name",
@"age":@"age",
@"department.id":@"department_id"
};
}
and then use the following whenever you want to serialize
the Employee
object 然后在要serialize
Employee
对象时使用以下命令
Employee *objEmployee = [Employee instanceFromDict:responseObject];
I hope it will work for you. 希望它对您有用。 All the best!! 祝一切顺利!!
OK, I got it from here: Mantle property class based on another property? 好的,我从这里得到了: 基于另一个属性的地幔属性类?
I modified the mapping dictionary to be like this 我将映射字典修改为这样
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name":@"name",
@"age":@"age",
NSStringFromSelector(@selector(department)) : @[@"department_id"]
};
}
and added: 并添加:
+ (NSValueTransformer *)departmentJSONTransformer {
return [MTLValueTransformer transformerUsingReversibleBlock:^id(Department *department, BOOL *success, NSError *__autoreleasing *error) {
return [MTLJSONAdapter JSONDictionaryFromModel:department error:nil];
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.