【发布时间】:2018-09-13 10:20:28
【问题描述】:
我正在从服务器(或文件)获取 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
相关:
【问题讨论】: