How to convert NSDictionary to NSString that contains json from NSDictionary to Swift?

How to convert an NSDictionary to an NSString that contains JSON from an NSDictionary? I tried, but to no avail

//parameters is NSDictionary let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary 

I want to convert this NSDictionary Json to NSString in swift

+7
swift
source share
1 answer

You can use the following code:

 var error: NSError? var dict: NSDictionary = [ "1": 1, "2": "Two", "3": false ] let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error) if let data = data { let json = NSString(data: data, encoding: NSUTF8StringEncoding) if let json = json { println(json) } } 

Given a NSDictionary , it is serialized as NSData and then converted to NSString .

The code that performs the conversion can also be rewritten more briefly:

Swift 3:

  do { let jsonData = try JSONSerialization.data(withJSONObject: data) if let json = String(data: data, encoding: .utf8) { print(json) } } catch { print("something went wrong with parsing json") } 

Original answer:

 if let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error) { if let json = NSString(data: data, encoding: NSUTF8StringEncoding) { println(json) } } 

Note that in order for serialization to work, the dictionary must contain valid keys and JSON values.

+15
source share

All Articles