O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.9. Serializing Arrays and Dictionaries into JSON

Problem

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.

Solution

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

Discussion

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
                    dataWithJSONObject:dictionary
                    options:NSJSONWritingPrettyPrinted
                    error:&error];

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required