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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access