Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 785
spa Avatar asked May 03 '26 16:05

spa


1 Answers

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;
};
like image 56
Paul de Lange Avatar answered May 06 '26 04:05

Paul de Lange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!