0

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?

Jigar Tarsariya
  • 3,189
  • 3
  • 14
  • 38
Mina Wissa
  • 10,923
  • 13
  • 90
  • 158

2 Answers2

0

first remove this code from your Employee.m file

@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

Employee *objEmployee = [Employee instanceFromDict:responseObject]; 

I hope it will work for you. All the best!!

Mandar Belkunde
  • 744
  • 1
  • 5
  • 10
0

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];
        }];

}
Community
  • 1
  • 1
Mina Wissa
  • 10,923
  • 13
  • 90
  • 158