How to use NSJSONSerialization

Logan Serman picture Logan Serman · Dec 2, 2011 · Viewed 219.2k times · Source

I have a JSON string (from PHP's json_encode() 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" and "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 JSON 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

rckoenes picture rckoenes · Dec 2, 2011

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);
   }
}