Serialize Objective-C Objects To JSON – iOS And JSON Part 1

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.

iOS defines some rules about the conversion from an object to JSON:

  • Top level object must be an NSArray of NSDictionary
  • For dictionaries, keys must be NSString objects
  • All objects in the hierarchy must be NSString, NSNumber, NSArray, NSDictionary or NSNull.

On to the code example…

Lines 2-14 create several types of arrays, packaging all of them into an array of arrays (objects). Line 14 creates a dictionary with a couple key/value pairs and also a key/value for the array of objects.

Line 22 demonstrates a nice feature of the Apple JSON serialization object, in that you can check if an object can be successfully converted to JSON. If so, on line 25 the serialization is completed, returning an NSData type.

Lines 28-34 print out the JSON to the debug console. The output will look as follows:

In the next post I’ll show you how to deserialize JSON into an object.