iOSGeek iOSGeek - 5 months ago 50
Objective-C Question

How to make a nested dictionary , IOS - Objective C

I am working on an iOS App with server communication. Can someone help me to build a dictionary like this.

{
"api_key": "APIKey",
"items": [{
"item_id": "10",
"quantity": "10"
}, {
"item_id": "11",
"quantity": "10"
}],
"user_id": "UserID",
"user_address": "address",
"user_number": "number"

}


Here is my code to create JSON which produce an invalid json

NSMutableArray *arrayItems = [NSMutableArray new];
for (int i=0; i<[ordeArray count]; i++) {
ItemBO *item = [ordeArray objectAtIndex:i];
NSString *quantity = [NSString stringWithFormat:@"%i",item.quantity];
NSDictionary *dic = @{@"quantity": quantity, @"item_id":item.itemID };
[arrayItems addObject: dic];
}
NSString * userID = [[NSUserDefaults standardUserDefaults] valueForKey:USERID];
NSDictionary *mainDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:

APIKEY, @"api_key",
orderinfo.deliveryAddress , @"delivery_address",
orderinfo.deliveryTime , @"delivery_time",
orderinfo.contactNumber , @"delivery_contact",
arrayItems , @"items",
userID , @"user_id",
nil];
return mainDictionary;

Answer

You can create dictionary by setting key-value pair its simple mechanism for dictionary.

In your case:

You have to take one array for items with object of item dictionary like:

NSDictionary *dic = @{
        "item_id": "10",
                   "quantity": "10"
    };

Add these type of objects in NSMutableArray like:

NSMutableArray *arrayItems = [NSMutableArray new];
[arrayItems addObject: dic];

These way you can add multiple dictionaries in this array after this done you can take another dictionary which holds all above key value pair like:

NSMutableDictionary *dicMain = [NSMutableDictionary new];
[dicMain setValue:"APIKey" forKey:"api_key"];
[dicMain setObject:arrayItems forKey:"items"]; // add items array in dictionary

and so on set all key-value pair and done thats it.

Convert this dictionary into JSON data using this

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithDictionary:dict] options:0 error:nil];

and set this data as request body.like this

[request setHTTPMethod:@"POST"];
[request setHTTPBody:objData];

Hope this might help you. :)