Deserialize JSON To Objective-C Objects – iOS And JSON Part 2

In Part 1 of the series Serialize Objective-C Objects to JSON I wrote a few examples for serializing objects into JSON. Specifically, a dictionary with several key/value pairs as well as an array. In this post I will show the opposite, how to deserialize JSON to Objective-C objects.

It’s important to note that the examples in both of these posts use the NSJSONSerialization class that Apple released beginning with iOS 5. For basic JSON serializing and deserializing no external library is required.

To keep the code focused on the task at hand, rather than include a bunch of networking code to acquire JSON, I will simulate the process and simply read JSON from a file that I’ve added to my project. The file contents are extracted from a Twitter API example that lists JSON for a sample search:

The JSON from the Twitter search follows:

Below I will describe how to deserialize the JSON above as well as demonstrate how to extract a few key/value pairs.

Deserialize JSON

The code example to deserialize JSON into objects follows. I’ll explain more about how things work after the code:

Lines 2-3 simulate a network download of JSON. The JSON show at the top of the post is stored in the file json.txt, which is read into an NSData object.

The code to deserialize is shown on line 8 – the JSON stored as NSData is the first parameter, there are several options for how the data is treated and the final parameter will contain an NSError object if something goes amiss.

The dictionary output for NSLog on line 13:

The code on lines 16-18 show how to extract from the JSON the string for the key ‘next_page’ using objectForKey to get the value from the dictionary.

The output for ‘next_page’ is below:

The final object retrieved from the JSON is an array, the relevant code is on lines 21-26. First a check is made to verify that the object for the key ‘results’ is an NSArray. From there, simply read the array and display the data. The output for ‘results’ array follows:

As you can see, serializing and deserializing with JSON is quite straightforward with Apple’s NSJSONSerialization class.