Swift 解析 json 无效
Swift parsing json doesn't work
我想解析一个 json 文件,这个在我的 json 文件中:
{
"currentPowerByClient": 0, <- i want to read this
"currentPowerToClient":518,
"tariff":1,
"totalGasDelivered":1061.004,
"totalPowerByClientHigh":10.704,
"totalPowerByClientLow":23.042,
"totalPowerToClientHigh":912.221,
"totalPowerToClientLow": 693.499
}
这是我的 swift 代码,名为 JSONResult
的对象包含我的 JSON
代码
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:
NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let item = jsonResult as NSDictionary? {
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary {
println(currentPowerByClient)
}
}
当我运行它时,它没有打印任何东西
行
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary
应该是
if let currentPowerByClient = item["currentPowerByClient"] as? NSNumber
因为item["currentPowerByClient"]
应该是一个数字,而不是字典。然后就可以了
我想解析一个 json 文件,这个在我的 json 文件中:
{
"currentPowerByClient": 0, <- i want to read this
"currentPowerToClient":518,
"tariff":1,
"totalGasDelivered":1061.004,
"totalPowerByClientHigh":10.704,
"totalPowerByClientLow":23.042,
"totalPowerToClientHigh":912.221,
"totalPowerToClientLow": 693.499
}
这是我的 swift 代码,名为 JSONResult
的对象包含我的 JSON
代码
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:
NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let item = jsonResult as NSDictionary? {
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary {
println(currentPowerByClient)
}
}
当我运行它时,它没有打印任何东西
行
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary
应该是
if let currentPowerByClient = item["currentPowerByClient"] as? NSNumber
因为item["currentPowerByClient"]
应该是一个数字,而不是字典。然后就可以了