How to Serialize Multi Level JSON Using RestKit

advertisements

I have my GET Method working and mapping my returned objects correctly. Now I am working on the POST Method. I need to serialize a Multi Level JSON, specifically it has 3 levels the in the following format

{
      "name": "Test",
      "version": "1",
      "iconId": 1,
      "runFrequency": 5,
      "lastActionSummary": "Yesterday, 9:30am",
      "description": "Test",
      "id": 1,
      "containers": [
            {
                  "id": 1,
                  "triggers": [
                        {
                              "@class": "someClass",
                              "intValue": 90,
                              "operator": "equal",
                              "type": "Ttest"
                        }
                  ]
            }
      ]
}

I tried do it like I do object Mapping for responses from the server but that failed due to the fact that containers never get added to the JSON. Any ideas on how I can achieve this? The restkit examples do not show multi Level JSON so they havent helped a great deal.


It seems like what you want here is a dictionary containing various fields:

NSMutableDictionary *topDictionary = [[NSMutableDictionary alloc] init];
[topDictionary setObject:@"Test" forKey:@"name"];
[topDictionary setObject:@"1" forKey:@"version"];
...

Then, you have an array of containers with a dictionary in each array item:

NSMutableArray *containers = [[NSMutableArray alloc] init];
[topDictionary setObject:containers forKey:@"containers"];
NSMutableArray *arrayItem1 = [[NSMutableDictionary alloc] init];
[containers addObject:arrayItem1];
[arrayItem1 setObject:[NSNumber numberWithInteger:1] forKey:@"id"];
...

Within each of the dictionaries under containers, you have a triggers array, again where each item of that array is a dictionary:

NSMutableArray *triggers = [[NSMutableArray alloc] init];
[arrayItem1 setObject:triggers forKey:@"triggers"];
NSMutableArray *trigger1 = [[NSMutableDictionary alloc] init];
[triggers addObject:trigger1];
[trigger1 setObject:@"someClass" forKey:@"@class"];
...

This just shows how to add 1 container with 1 trigger in that container, but you get the idea. Convert to the appropriate loops if you want to put more than one item in each array.

Once you have these dictionaries (within an array, within a dictionary, within an array, within a dictionary...) you then have an object that can be serialized to JSON cleanly.