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 using Swift


Of course, you can invoke the NSJSONSerialization.dataWithJSONObject method from Swift, too, which returns an NSData object that you can then convert to a string.

How to do it…

Here's a simple example:

var error: NSError?
var data: NSJSONSerialization.dataWithJSONObject(
  dictionary, 
  options: NSJSONWritingOptions(0),
  error: &error);
var json: NSString(data: data, encoding: NSUTF8StringEncoding); 

How it works…

The method dataWithJSONObject operates just as its Objective-C counterpart does. Once we receive NSData containing the JSON-encoded version of the dictionary, we convert it to NSString using the NSString constructor.