Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


JSON to NSDictionary

How does the first line of code convert JSON data to NSDictionary objects, can someone please explain these two lines of code

NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

NSArray *blogPostArray = [jsonDictionary objectForKey:@"posts"];

1 Answer

Amit Bijlani
Amit Bijlani
Treehouse Guest Teacher

The NSJSONSerialization class contains the logic to convert JSON data into NSArray or NSDictionary. The second line is simply retrieving an array from the key posts of the jsonDictionary. Here's an explanation of NSDictionary

Please correct me If I am wrong, the entire json response/data is converted into a single NSDictionary object, right? How is the data inside the posts key is also converted to an array of NSDictionary objects?

Amit Bijlani
Amit Bijlani
Treehouse Guest Teacher

You are right. If you see the documentation for NSJSONSerialization you will see that it says:

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

The data inside the posts key is converted to an array as part of the JSON parsing performed by the NSJSONSerialization class.

ok got it, thank you. Any idea when can we expect some tutorials on iphone/ipad game development.