0
votes

I'm trying to map a object through the following JSON:

{
  "main_email": {"id": 1, "address": "[email protected]"},
  "id": 1, 
  "first_name": "first name", 
  "last_name": "last name", 
}

I have a object called User with the properties:

@property (nonatomic, assign) NSInteger userID;
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, strong) Email *mainEmail;

And the object Email have the properties:

@property (nonatomic, assign) NSInteger emailID;
@property (nonatomic, copy) NSString *emailAddress;

Now i'm mapping in the User like bellow:

RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]];
[userMapping addAttributeMappingsFromDictionary:@{@"id": @"userID",
                                          @"first_name": @"firstName",
                                           @"last_name": @"lastName"}];
RKObjectMapping *emailMapping = [RKObjectMapping mappingForClass:[Email class]];
[emailMapping addAttributeMappingsFromDictionary:@{@"main_email.id": @"emailID",
                                              @"main_email.address": @"emailAddress"}];
[userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mainEmail"
                                                                            toKeyPath:@"mainEmail"
                                                                          withMapping:emailMapping]];

This code keeps returning a empty Email object in User.mainEmail

1

1 Answers

0
votes

First off your property mapping should be fromKeyPath:@"main_email" toKeyPath:@"mainEmail" the fromKeyPath is the key path in the JSON and the toKeyPath is the attribute/relationship in CoreData.

Second in your email mapping you don't need to prefix each key path with "main_email." when RestKit does nested mapping it will handle this for you (assuming your property mapping is set up properly)

Here is your example with those changes:

RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class];
[userMapping addAttributeMappingsFromDictionary:@{@"id": @"userID",
                                          @"first_name": @"firstName",
                                           @"last_name": @"lastName"}];
RKObjectMapping *emailMapping = [RKObjectMapping mappingForClass:[Email class]];
[emailMapping addAttributeMappingsFromDictionary:@{@"id": @"emailID",
                                              @"address": @"emailAddress"}];
[userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"main_email"
                                                                            toKeyPath:@"mainEmail"
                                                                          withMapping:emailMapping]];