Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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

like image 802
Gayathri Avatar asked Feb 12 '15 08:02

Gayathri


1 Answers

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.

like image 191
Antonio Avatar answered Nov 15 '22 03:11

Antonio