O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

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

Generating JSON on iOS in Objective-C

You can also use the NSJSONSerializer class to serialize NSDictionary or NSArray; simply use the dataWithJSONObject method.

How to do it…

Here's a simple example assuming that data is NSDictionary you want to convert to JSON:

NSError *error;
NSData* jsonData = [NSJSONSerialization
dataWithJSONObject: data
options: NSJSONWritingPrettyPrinted
error: &error];

How it works…

The dataWithJSONObject:options:error method can take NSArray or NSDictionary and returns an NSData blob with the encoded JSON of the collection you passed. If you pass kNilOptions, the JSON will be encoded in a compact manner; for pretty-printed JSON, pass the option NSJSONWritingPrettyPrinted instead.

See also

Apple's documentation for the NSJSONSerialization ...

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