11.9. Serializing Arrays and Dictionaries into JSON


You want to serialize a dictionary or an array into a JSON object that you can transfer over the network or simply save to disk.


Use the dataWithJSONObject:options:error: method of the NSJSONSerialization class.


The dataWithJSONObject:options:error: method of the NSJSONSerialization class can serialize dictionaries and arrays that contain only instances of NSString, NSNumber, NSArray, NSDictionary variables, or NSNull for nil values. As mentioned, the object that you pass to this method should be either an array or a dictionary.

Now let’s go ahead and create a simple dictionary with a few keys and values:

NSDictionary *dictionary =
  @"First Name" : @"Anthony",
  @"Last Name" : @"Robbins",
  @"Age" : @51,
  @"children" : @[
          @"Anthony's Son 1",
          @"Anthony's Daughter 1",
          @"Anthony's Son 2",
          @"Anthony's Son 3",
          @"Anthony's Daughter 2"

As you can see, this dictionary contains the first name, last name, and age of Anthony Robbins. A key in the dictionary named children contains the names of Anthony’s children. This is an array of strings with each string representing one child. So by this time, the dictionary variable contains all the values that we want it to contain. It is now time to serialize it into a JSON object:

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization

if ([jsonData length] > 0 && error == nil){
    NSLog(@"Successfully ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.