2

我有以下 JSON:

{
    "users": [
        {"id": "1", "name": "John Doe"},
        {"id": "2", "name": "Bill Nye"}
    ],
    "groups": [
        {"id": "1", "name": "Group1", "users": ["1", "2"]},
        {"id": "2", "name": "Group2", "users": ["1"]}
    ]
}

...以及带有用户和组对象的核心数据模型。组对象与用户具有一对多关系 (NSSet)。

我发现以下线程似乎表明这是可能的,但没有解释如何执行这种映射:

https://github.com/RestKit/RestKit/issues/284

如何执行此映射以正确连接每个组的“用户”关系?

注意:我已经设置了正确地将 JSON 用户和组映射到其各自的核心数据对象的映射。但是,每个组的“用户”NSSet 是空的。

4

2 回答 2

3

因此,我使用 RestKit 0.20(pre2) 解决了这个问题。

JSON 需要更改为以下内容(注意组的 users 数组中的属性名称):

{
    "users": [
        {"id": "1", "name": "John Doe"},
        {"id": "2", "name": "Bill Nye"}
    ],
    "groups": [
        {"id": "1", "name": "Group1", "users": [{"id" : "1"}, {"id" : "2"}]},
        {"id": "2", "name": "Group2", "users": [{"id" : "1"}]}
    ]
}

然后,以下映射:

RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
userMapping.identificationAttributes = @[@"id"];
[userMapping addAttributeMappingsFromArray:@[@"id", @"name"]];
RKEntityMapping *groupMapping = [RKEntityMapping mappingForEntityForName:@"Group" inManagedObjectStore:managedObjectStore];
groupMapping.identificationAttributes = @[@"id"];
[groupMapping addAttributeMappingsFromArray:@[@"id", @"name"]];
[groupMapping addRelationshipMappingWithSourceKeyPath:@"users" mapping:userMapping];

最后,以下 responseDescriptors:

RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:@"/api/allthejson" keyPath:@"users" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKResponseDescriptor *groupResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:@"/api/allthejson" keyPath:@"groups" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptorsArray:@[userResponseDescriptor, groupResponseDescriptor]];

然后使用 RKObjectManager 的 getObjectsAtPath:parameters:success:failure 方法获取您的对象,您就完成了!

于 2012-12-06T19:22:44.563 回答
1

RestKit 有很多问题,尤其是在建模关系方面。调试映射可能令人生畏。

这是一些处理您在没有 RestKit 的情况下描述的代码。

NSArray *userArray; 
// an array populated with NSManagedObjects 
// correctly converted from JSON to the User entity

NSArray *groups = [jsonObject objectForKey:@"groups"];

for (NSDictionary *d in groups) {
   Group *g = [NSEntityDescription insertNewObjectForEntityForName:@"Group"
                  inManagedObjectContext:_managedObjectContext];
   g.id = @([d[@"id"] intValue]);
   g.name = d[@"name"];
   NSArray *users = d[@"users"];
   for (NSString *s in users) {
      User *u = [[userArray filteredArrayUsingPredicate:
        [NSPredicate predicateWithFormat:@"id = %@", @([s intValue])]]
          objectAtIndex:0];
      [g addUsersObject:u];
   }
}
// save
于 2012-12-05T16:58:34.527 回答