2016/05/12

Dictionary to JSON string and JSON string to dictionary

Updated for Swift 4 on 2017/09/06 - Because I always end up Googling NSJSONSerialization and its options...

Dictionary to JSON string

The dictionary is converted to Data which contains an UTF8 encoded string inside.
let dictionary = ["nacho": ["1","2","3"]]
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString)
{"nacho":["1","2","3"]}
Also it is possible to use .prettyPrinted but in reality I never use it.

JSON String to Dictionary

The JSON string should be converted to NSData (using UTF8 encoding), then we can create a dictionary from such data.
let jsonString = "{\"nacho\":[\"1\",\"2\",\"3\"]}"
let jsonData = jsonString.data(using: .utf8)
let dictionary = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableLeaves)
print(dictionary!)
{\n    nacho =     (\n        1,\n        2,\n        3\n    );\n}
In NSJSONReadingOptions there is also .mutableLeaves, .allowFragments, etc but I barely use them

0 comments :