How to convert NSDictionary to NSString which contains json of NSDictionary in Swift?

i0S Swift Issue

Question or problem in the Swift programming language:

How to convert NSDictionary to NSString which contains JSON of NSDictionary ? I have tried but without success

//parameters is NSDictionary

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

I want convert this NSDictionary Json to NSString in swift

How to solve the problem:

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, then converted to NSString.

The code doing the conversion can also be rewritten more concisely as:

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 the serialization to work the dictionary must contain valid JSON keys and values.

Hope this helps!