objective-ciosrestkit

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...


Solution

  • 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;
    };