O'Reilly logo

iOS 5 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

8.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 either be an array or a dictionary.

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

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

[dictionary setValue:@"Anthony"
              forKey:@"First Name"];

[dictionary setValue:@"Robbins"
              forKey:@"Last Name"];

[dictionary setValue:[NSNumber numberWithUnsignedInteger:51]
              forKey:@"Age"];

NSArray *arrayOfAnthonysChildren = [[NSArray alloc]
                                    initWithObjects:
                                    @"Anthony's Son 1",
                                    @"Anthony's Daughter 1",
                                    @"Anthony's Son 2",
                                    @"Anthony's Son 3",
                                    @"Anthony's Daughter 2",
                                    nil];

[dictionary setValue:arrayOfAnthonysChildren
              forKey:@"children"];

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 ...

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