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:
I’ve written previously on how to serialize Objective-C objects to JSON as part of a simple Flickr photo viewer. At the time, Apple did not have support for JSON directly within the frameworks, therefore my examples used an open source JSON library. However, since iOS 5 app developers have had the opportunity to use the NSJSONSerialization class to convert objects to JSON and vice versa.
This tutorial will show you how to convert several objects into JSON. With most of my code examples I like to keep things pretty simple, so you can walk away with some working code as a starting point for your own work. This tip is no exception: I’ll create a dictionary object that contains several key/value pairs. I’ll also add an array of objects to the dictionary. I’ll use NSJSONSerialization object to serialize the dictionary into JSON.
Two consistently popular posts on are iPhone JSON Frameworks for iPhone Part 1 and Part 2. Seems a good time to revisit the combination of the iPhone and JSON, this time creating a complete working application.
This is part one of a three part series in which I’ll build a Flickr photo viewer, a pretty simple application, however, we’ll cover some interesting stuff with the primary goal of understanding the nuts and bolts of working with JSON to build a complete working application accessing web-services.
Editor’s Note: Due to the popularity of this iPhone JSON series, a new three part tutorial series on working with JSON was published in August 2009. You can find the latest JSON iPhone tutorial series at the links below:
- iPhone JSON and Flickr Tutorial – Part 1
- iPhone JSON and Flickr Tutorial – Part 2
- iPhone JSON and Flickr Tutorial – Part 3
If you’ve found a need to work with JSON and the iPhone, Stig Brautaset has written a nice framework that is available on github.
This framework implements a strict JSON parser and generator in Objective-C. It’s easy to work with and can be used across any number of projects with ease.