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…

// Empty array
NSArray *emptyArray = @[];
// Single element array
NSArray *singleElementArray = @[@"Error Message"];
// Array of strings
NSArray *arrayOfStrings = @[@"First Name", @"Last Name"];
// Array of above arrays
NSArray *arrayOfObjects = @[emptyArray, singleElementArray, arrayOfStrings];

// Dictionary with several kay/value pairs and the above array of arrays
NSDictionary *dict = @{@"BlogName" : @"iOS Developer Tips",
                    @"BlogDomain" : @"",
                    @"Array" : arrayOfObjects};

NSError *error = nil;
NSData *json;

// Dictionary convertable to JSON ?
if ([NSJSONSerialization isValidJSONObject:dict])
  // Serialize the dictionary
  json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

  // If no errors, let's view the JSON
  if (json != nil && error == nil)
    NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
    NSLog(@"JSON: %@", jsonString);
    [jsonString release];      

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:

  "Array" : [

      "Error Message"
      "First Name",
      "Last Name"
  "BlogName" : "iOS Developer Tips",
  "BlogDomain" : ""

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