Basic JSON parsing in iOS

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:

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.

  • Andrew Larking

    Lovely little walk through, thanks. This saved me a fair chunk of time.

  • mannam koteswararao

    Thanks it’s very helpfull

  • Nuno Bastos

    You are fantastic. Only now I understand how JSON it works.

    I read highly varied documentation and had never understood.

    Many, many thanks …

  • Phillip Flores

    I’m glad I came across this. Spent a lot of time looking at other examples on how to access a web service and retrieve the data to no avail. Very clear and concise explanation. Thanks again.

  • Pex Xep

    This is so great tutorial. But how to fetcher another day at the same time?

  • Jonathan García

    “Just remember that anything surrounded with { } is a dictionary, and anything surrounded with[ ] is an array.” good tip

  • Nhexia

    what a simple code! :D, can u add function to populate a table view for the result? thanks and more power! nhexia


Click Here