0

我想用来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

和员工类:

#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 不是 Employee 的属性。”

这里有什么问题?有没有办法将对象序列化为单个字典,而不是将部门对象嵌套在员工对象中?

4

2 回答 2

0

首先从您的 Employee.m 文件中删除此代码

@implementation Employee
+ (NSDictionary *)JSONKeyPathsByPropertyKey {

    return @{
             @"name":@"name",
             @"age":@"age",
             @"department.id":@"department_id"
             };
}

serialize然后在您想要Employee对象时使用以下内容

Employee *objEmployee = [Employee instanceFromDict:responseObject]; 

我希望它对你有用。一切顺利!!

于 2016-06-23T13:53:59.490 回答
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];
        }];

}
于 2016-06-23T14:37:21.117 回答