Logan Serman Logan Serman - 10 months ago 104
Objective-C Question

How to use NSJSONSerialization

I have a JSON string (from PHP's

that looks like this:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys
"id" => "1"
"name" => "Aaa"

I do not understand how the NSJSONSerialization stores the data though. Here is my code so far:

NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];

This is just something I saw as an example on another website. I have been trying to get a read on the
object by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS.

How do I use NSJSONSerialization to parse the JSON above, and turn it into the data structure I mentioned?

Answer Source

Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);