Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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.