10

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

Antonio
  • 71,651
  • 11
  • 148
  • 165
Gayathri
  • 163
  • 2
  • 2
  • 10

1 Answers1

22

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.

Jakub
  • 13,712
  • 17
  • 82
  • 139
Antonio
  • 71,651
  • 11
  • 148
  • 165
  • @EyalBenYehuda the most obvious answer to your question is: __just try it__!! You should find any answer you may have by reading [the documentation](https://developer.apple.com/reference/foundation/jsonserialization), but the answer is yes, it works with nested dictionaries and arrays – Antonio Dec 10 '16 at 16:57
  • Thanks @Antonio, i did tried before but nothing worked. i finally got it to work( http://stackoverflow.com/a/41091453/1334575 ). thanks to your answer (with a small variation i saw here: https://www.raywenderlich.com/120442/swift-json-tutorial). thanks. – Eyal Ben Yehuda Dec 11 '16 at 21:45
  • Thank god, i've been looking for an hour. The NSString idea is perfect. – Florensvb Mar 09 '17 at 16:07
  • Updated for Swift 5: `JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted)` – Unterbelichtet Apr 01 '21 at 11:43