我从服务器(或文件)获取了一个JSON字符串。
我想解析这个JSON字符串,动态地确定每个值的类型。
然而,在布尔值方面,JSONSerialization
只是将值转换为0
或1
,代码无法区分“0”是Double
、Int
还是Bool
。
我希望能够识别出值是否为Bool
,而不必明确知道特定键对应于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
相关: