I am getting a JSON string from the server (or file).
I want to parse that JSON string and dynamically figure out each of the value types.
However, when it comes to boolean values, JSONSerialization
just converts the value to 0
or 1
, and the code can't differentiate whether "0" is a Double
, Int
, or Bool
.
I want to recognize whether the value is a Bool
without explicitly knowing that a specific key corresponds to a Bool
value. What am I doing wrong, or what could I do differently?
// What currently is happening:
let jsonString = "{\"boolean_key\" : true}"
let jsonData = jsonString.data(using: .utf8)!
let json = try! JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String:Any]
json["boolean_key"] is Double // true
json["boolean_key"] is Int // true
json["boolean_key"] is Bool // true
// What I would like to happen is below (the issue doesn't happen if I don't use JSONSerialization):
let customJson: [String:Any] = [
"boolean_key" : true
]
customJson["boolean_key"] is Double // false
customJson["boolean_key"] is Int // false
customJson["boolean_key"] is Bool // true
Related: