Sandbox
Sandbox

Reputation: 8188

How to add NSDictionary to another NSDictionary before serializing to json

I am new to ios programming. I put my data in NSDictionary and then use AFJSONRequestSerializer to serialize to json before sending it to the server.

Now if my json has simple structure like key -> value pairs, then I can easily do it but what if my structure is like this -

"person" =     (
                {
                    "location" =             {
                        city = "Manila";
                        Country = "Phillipines";
                    };
            image = "http://mymanila.com/1.png";
            link ="http://mymanila.com/1.html"
        }
    );

My problem is how do I put location, which itself is another dictionary with key-value pair? Thanks.

Upvotes: 0

Views: 146

Answers (2)

puru020
puru020

Reputation: 818

Like this:

NSMutableDictionary* person = [NSMutableDictionary dictionary];

NSDictionary* location = @{@"city":@"Manila", @"Country":@"Phillipines"};
[person setObject:location forKey:@"location"];
[person setObject:@"http://mymanila.com/1.png" forKey:@"image"];
[person setObject:@"http://mymanila.com/1.html" forKey:@"link"];

Then you can convert this to JSON like this:

NSData *dictData = [NSKeyedArchiver archivedDataWithRootObject:person];
id jsonObject = [NSJSONSerialization JSONObjectWithData:dictData options:NSJSONReadingMutableContainers error:nil];

Upvotes: 0

Rafał Sroka
Rafał Sroka

Reputation: 40028

Here you go.

NSDictionary *locationDictionary = @
{
    @"city" : @"Manila",
    @"Country" : @"Phillipines"
};


NSDictionary *personDictionary = @
{
    @"location" : locationDictionary,
    @"image" : @"http://mymanila.com/1.png",
    @"link" : @"http://mymanila.com/1.html"
};

NSDictionary *fullDictionary = @
{
    @"person" : personDictionary
};

And now, just serialize the fullDictionary.

Upvotes: 2

Related Questions