Reputation: 300
I'm trying to make a dynamic mapping for a bit weird structured JSON. I have "array mapped to object" sort of thins so that array indices ake keys e.g.:
{
"0": {object},
"1": {another object},
"2": {yet another object},
...
}
All objects are of the same type so they can be parsed using the same mapping, but how to deal with varying key names?
Upvotes: 1
Views: 857
Reputation: 1000
Check out the section on "Handling Dynamic Nesting Attributes" in the Object Mapping docs.
He walks through an example (copied here) with the JSON:
{ "blake": {
"email": "[email protected]",
"favorite_animal": "Monkey"
}
}
Corresponding to the User class:
@interface User : NSObject
@property (nonatomic, retain) NSString* email
@property (nonatomic, retain) NSString* username;
@property (nonatomic, retain) NSString* favoriteAnimal;
@end
Which, you'll notice, the username property corresponds to the key of the JSON.
In order to map it, he uses a special parenthesis syntax to indicate that they key itself is a property:
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class] ];
[mapping mapKeyOfNestedDictionaryToAttribute:@"username"];
[mapping mapFromKeyPath:@"(username).email" toAttribute:"email"];
[mapping mapFromKeyPath:@"(username).favorite_animal" toAttribute:"favoriteAnimal"];
Hope this helps!
Upvotes: 3