2016/05/12

Dictionary to JSON string and JSON string to dictionary

Because I always end up Googling NSJSONSerialization and its options...

Dictionary to JSON string

The dictionary is converted to NSData which contains an UTF8 encoded string inside.
let dictionary: [String: AnyObject] = ["nacho": ["1","2","3"] ]
let jsonData = try? NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions())
let jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
print(jsonString)
{"nacho":["1","2","3"]}
Also it is possible to use .PrettyPrinted

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.dataUsingEncoding(NSUTF8StringEncoding)
let dictionary = try? NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableLeaves)
print(dictionary!)
{\n    nacho =     (\n        1,\n        2,\n        3\n    );\n}
In NSJSONReadingOptions there is also .MutableLeaves and .AllowFragments but I barely use them

0 comments :