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 which is nice for showing the result string to humans, but in reality I almost 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)
Optional(["nacho": ["1", "2", "3"]])
In JSONReadingOptions there is also .mutableLeaves, .allowFragments, etc but I don't use them very often (Mutable leaves will create a mutable dictionary which might sound helpful but in reality you want to handle things as few as possible in dictionaries since its information is not always statically typed and programmers are able to add/remove key/values without the compiler knowing about it).

Accessing information from objects created with JSONSerialization.jsonObject

Now, since JSONSerialization.jsonObject returns an object of type Any we need to cast it (according to our needs) to be able to access its information. For example:
if let personsDictionary = dictionary as? [String: Any] {
    print(personsDictionary)
    if let numbers = personsDictionary["nacho"] as? [String] {
        print(numbers)
    }
}
["nacho": ["1", "2", "3"]]
["1", "2", "3"]
Hope it helps.

0 comments :