我有以下 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 是空的。
所以,我使用 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 方法获取您的对象,您就完成了!
关于objective-c - RestKit - 水合外键数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13726203/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |