【问题标题】:Swift parsing json doesn't workSwift解析json不起作用
【发布时间】:2015-01-01 12:10:03
【问题描述】:

我要解析一个 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)
    }
}

当我运行它时,它不打印任何东西

【问题讨论】:

  • 也许你应该使用error参数;知道 jsonResult 是 nil 还是与 NSDictionary 不同的东西会很有帮助
  • 我没有收到任何错误,也许 jsonResult 是 nil,但我不知道为什么它是 nil
  • 所以您确实更改了代码以实际使用错误参数并且您没有收到任何错误或者您没有收到上述代码的任何错误?
  • 我只是没有收到错误,也许我解析 json 的方式是错误的

标签: ios json swift


【解决方案1】:

线

if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary

应该是

if let currentPowerByClient = item["currentPowerByClient"] as? NSNumber

因为item["currentPowerByClient"] 应该是一个数字,而不是字典。然后就可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    相关资源
    最近更新 更多