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 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.

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