spa
spa

Reputation: 5205

Nested objects in NSDictionary with RestKit

I have a JSON document which contains objects with known schema in an object with unknown keys and I'll like to map that with RestKit. Let me explain this:

{
    "object":
    {
        "unknownKey1" : {"data1" : "...", "data2" : "..."},
        "unknownKey2" : {"data1" : "...", "data2" : "..."},
        "unknownKey3" : {"data1" : "...", "data2" : "..."}
    }
}

The setup of the object with key "object" is only known at runtime. The keys included in the object have random names. However, I know the exact schema of the objects stored at these unknown keys.

Now I would like to map the content of the object with key "object" to a NSDictionary as it provides easy access to the random keys. However, as the schema of the objects stored at these keys is known, I would like them to be mapped to custom objects.

So is there a possibility to map to a NSDictionary containing these objects? I haven't found a solution...

Upvotes: 3

Views: 1288

Answers (3)

Sasan Soroush
Sasan Soroush

Reputation: 925

When you have a JSON Structure like this:

{
  "blake": {        
    "email": "[email protected]",        
    "favorite_animal": "Monkey"    
  },    
  "sarah": {
    "email": "[email protected]",   
    "favorite_animal": "Cat"
  }
}

You can map it like this:

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class] ];
mapping.forceCollectionMapping = YES;
[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"username"];
[mapping addAttributeMappingsFromDictionary:@{
    @"(username).email": @"email",
    @"(username).favorite_animal": "favoriteAnimal"
}];

You can read more at RestKit Documentation

Upvotes: 1

AndyDev
AndyDev

Reputation: 1409

Maybe check out JSONKit https://github.com/johnezang/JSONKit to create a NSDictionary from your JSON document.

Upvotes: 0

Paul de Lange
Paul de Lange

Reputation: 10633

You could do something like this:

RKObjectMapping* mapping = [RKDynamicObjectMapping dynamicMapping];
mapping.objectMappingForDataBlock = ^(id data) {
    NSDictionary* object = [data objectForKey: @"object"];
    NSArray* keys = [object allKeys];

    RKObjectMapping* dataMapping = [RKObjectMapping objectMapping];
    //Use the keys to define mapping
    return dataMapping;
};

Upvotes: 3

Related Questions