651.288.7000 info@intertech.com

While there are many 3rd party APIs available to help simplify working with JSON in the context of other tools (such as Core Data and RESTful WebServices), this article focuses on how one can use the “out of the box” support included in the Foundation framework.

As of iOS 5, the Foundation framework includes a class (NSJSONSerialization) that can easily transform an NSData-JSON object into an NSDictionary.  So for this example, the dictionary keys are: “Monday,” “Tuesday,” and “Wednesday.”  The value of each weekday is an NSArray of nested individual courses.  Each course, in turn, is represented as another NSDictionary.

Let’s assume this is the JSON document, which is located on a remote site:

This document can be downloaded with a simple method call from NSData:

 

iOS

 

Next we need to transform this NSData-JSON object into an NSDictionary.  The keys of this dictionary are “Monday, “Tuesday,” and “Wednesday.”  Like many API methods of Cocoa Touch, this expects the address of an NSError pointer.  If something goes wrong, the API method will create an NSError object and update the pointer accordingly.

Notice that we set the “options” parameter with NSJSONReadingMutableContainers. This tells the NSJSONSerialization object that the document should be transformed into mutable collections (i.e., NSMutuableDictionary and NSMutuableArray).  Other reading options include: NSJSONReadingMutuableLeaves (String values should be transformed into NSMutuableStrings), and NSJSONReadingAllowFragments (permit top level objects that are not an NSArray, NSDictionary, or any subclass).

Multiple reading options can be added with the ‘|’ operator:

To specify no options, use kNilOptions:

At this point, as long as the NSError pointer is nil, we can access each dictionary and array key as needed.  Just remember that anything surrounded with { } is a dictionary, and anything surrounded with [ ] is an array.

Pin It on Pinterest

Share This

Like What You've Read?

Subscribe to the Blog.

Every Friday we send that week's content from our Developers via email. Try it out!

You have Successfully Subscribed!