I'm dealing with the following json:
{
"status":
{
"errorCode":{errCode},
"errorMsg":{errMsg},
},
"data":
{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
}
I need to use different mapping for the object in data
, according to errCode
value. I tried to use RKDynamicMapping, but got confused with the keyPaths..
Is there any way to achieve that?
Edit:
I'm using this code:
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];
Well, basically this code works, but I have couple of issues with it:
- It seems very ugly to keep writing "data.x" for each attribute of the mapping.
The result dictionary comes back with
NSNull
as the key for the "data" mapping. (its value is fine though..)status = "<ServerStatusCode: 0x155b2fa0>"; "<null>" = "Info: 0x15535800>";
Technically when you create the dynamic mapping it should be:
Note the
@0
, because you should be passing an object (NSNumber
), not a plain number (where 0 will equate to nil and another number will cause problems).The other 2 complaints you have are just the way things are. The first is because you need to index into the data. Both are caused by the
keyPath:nil
, specifying that the data is accessed from the top level and that there is no key with which to access the result.