Search code examples
objective-cjsoncocoa-touchnsjsonserialization

Cocoa Touch JSON Handling


I've been looking for a while now and I can't seem to find a solution.

I am trying to format a JSON object that is being held in an NSData *receivedData.

The format of the JSON is:

[ { "name":"Stephen", "nickname":"Bob" }, { "name":"Rob", "nickname":"Mike" }, { "name":"Arya", "nickname":"Jane" } ]

Normally I would use "NSJSONSerialization JSONObjectWithData:" of the NSDictionary. Then I would normally take the root of the JSON (in this case it would be something like "People":) and create the array from that root object. However as you can see this response is simply an array without a root object. I'm not sure how to handle this. The end goal is to have an array of Person objects, populated with the data in the JSON.

Edit: I would also like to add that I want to keep it native without third party libraries.


Solution

  • OK for anyone reading this. I just figured it out. Instead of formatting the initial NSData into a dictionary, you put that straight into an array. Then create a dictionary for each object in the array. Like so:

    NSArray *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSDictionary* json = [responseArray objectAtIndex:0];
    NSLog (@"%@",[json objectForKey:@"nickname"]);