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
, NS
Array
, 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 ...
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.