使用RESTKIT映射嵌套对象

时间:2014-11-03 20:25:04

标签: ios objective-c mapping restkit

我正在尝试通过以下JSON映射对象:

{
  "main_email": {"id": 1, "address": "mainemail@email.com"},
  "id": 1, 
  "first_name": "first name", 
  "last_name": "last name", 
}

我有一个名为User的对象,其属性为:

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

对象Email具有以下属性:

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

现在我在用户中映射如下:

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

此代码在User.mainEmail

中不断返回空的Email对象

1 个答案:

答案 0 :(得分:0)

首先,您的属性映射应为fromKeyPath:@"main_email" toKeyPath:@"mainEmail" fromKeyPath是JSON中的关键路径,toKeyPath是CoreData中的属性/关系。

在电子邮件映射中,您不需要为每个密钥路径添加前缀“main_email”。当RestKit执行嵌套映射时,它将为您处理(假设您的属性映射设置正确)

以下是这些更改的示例:

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