我有以下JSON:
{
"IdList": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
],
“Persons”: [
{
"Id": 2,
"Name": “James”,
"Description": “Tall”,
"Items": [
{
"Id": 1051,
"Name": “Hat”,
"Description": "",
“Accesories”: []
}]
]}
我这样使用RKResponseDescriptor就是这样:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[MappingProvider validationMapping] method:RKRequestMethodGET pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self addResponseDescriptor:responseDescriptor];
我的验证映射包含以下内容:
+ (RKDynamicMapping *)validationMapping {
RKDynamicMapping * dynamicMapping = [RKDynamicMapping new];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
NSArray *personsAray = [representation objectForKey:@"Persons"];
if (!personArray || !personArray.count) {
//Fail operation no contents
return nil;
}else {
NSArray *idsArray = [representation objectForKey:@"IdList"];
if (!idsArray || !idsArray.count) {
//Fail operation no contents
return nil;
}else {
if (idsArray) {
[[NSUserDefaults standardUserDefaults] setObject:idsArray forKey:kIds];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSArray *categoryArray = [menuArray valueForKey:@"Items"];
if (!categoryArray || !categoryArray.count) {
return nil;
}else {
// If we have some data map the response!
return [self theMapping];
}
}
return nil;
}];
return dynamicMapping;
}
+ (RKEntityMapping *)theMapping {
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Person" inManagedObjectStore:[[CoreDataManager sharedInstance] objectStore]];
// I want to start the mapping from Person, how do I do that?
[mapping mappingForSourceKeyPath:@"Persons"];
mapping.assignsNilForMissingRelationships = YES;
mapping.assignsDefaultValueForMissingAttributes = YES;
[mapping addAttributeMappingsFromDictionary:@{
@"Id": @"remoteID",
@"Name": @"name",
}];
mapping.identificationAttributes = @[ @"remoteID" ];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"Items"
toKeyPath:@"misc"
withMapping:[MappingProvider productMapping]]];
return mapping;
}
如何告诉restKit从我的" theMapping"中的Persons键路径开始映射?方法?我尝试过使用[mapping mappingForSourceKeyPath:@"Persons"];
,但没有运气。
答案 0 :(得分:1)
在这种情况下,您通常会使用2个响应描述符。
您的第一个响应描述符将使用动态映射,其关键路径为IdList
。这有点滥用并将representation
存储到用户默认值并返回nil。
你的第二个响应描述符将使用关键路径Items
的常规映射(通过它的外观,尽管你的代码使用未定义的变量)并且如果没有结果则依赖RestKit来不执行任何映射(尽管在你有一个删除的获取请求块的情况下你需要使用另一个动态映射。)
mappingForSourceKeyPath:
使用指定的密钥路径返回接收器上的属性映射,因此与您尝试执行的操作完全无关。它是响应描述符中的关键路径,可以深入到数据结构中。您可以使用映射中的关键路径钻取,但是可以钻取到对象中,而不是字典。