我正在处理以下json:
{
"status":
{
"errorCode":{errCode},
"errorMsg":{errMsg},
},
"data":
{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
}
我需要根据data
值为errCode
中的对象使用不同的映射。我试图使用RKDynamicMapping,但与keyPaths混淆..
有没有办法实现这个目标?
修改
我正在使用此代码:
RKObjectMapping *infoMapping = [RKObjectMapping mappingForClass:[Info class]];
[infoMapping addAttributeMappingsFromDictionary:@{@"data.key1":@"key1", @"data.key2":@"key2", @"data.key3:@"key3}];
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"status.errorCode" expectedValue:0 objectMapping:infoMapping]];
[dynamicActivateTravelMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
NSNumber *errorCode = [[representation valueForKey:@"status"] valueForKey:@"errorCode"];
if ([errorCode integerValue] == WSErrorUnknown) {
return unknownMapping;
}
else{
return infoMapping;
}
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dynamicMapping method:RKRequestMethodPOST pathPattern:kResource keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];
嗯,基本上这段代码可行,但我有几个问题:
结果字典返回NSNull
作为“数据”映射的关键字。 (虽然它的价值很好......)
status = "<ServerStatusCode: 0x155b2fa0>";
"<null>" = "Info: 0x15535800>";
答案 0 :(得分:1)
从技术上讲,当您创建动态映射时,它应该是:
[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"status.errorCode" expectedValue:@0 objectMapping:infoMapping]];
请注意@0
,因为您应该传递一个对象(NSNumber
),而不是一个普通数字(其中0将等于nil而另一个数字会导致问题)。
你提出的另外两项投诉就是事情的方式。首先是因为您需要索引数据。两者都是由keyPath:nil
引起的,指定从顶层访问数据,并且没有用于访问结果的键。