Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.