I want to use Mantle
to serialize some objects to this 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:
#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."
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?
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];
}];
}