我从服务器(或文件)获取 JSON 字符串。
我想解析那个 JSON 字符串并动态找出每个值类型。
但是,当涉及到布尔值时,JSONSerialization
只需将值转换为0
or 1
,代码无法区分“0”是 a Double
、Int
还是Bool
。
Bool
我想在不明确知道特定键对应于值的情况下识别该值是否为a Bool
。我做错了什么,或者我可以做些什么不同的事情?
// 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
有关的: