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.

Get JavaScript JSON 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.