【问题标题】:getting nil value while parsing JSON in swift using Alamofire使用 Alamofire 快速解析 JSON 时获取 nil 值
【发布时间】:2019-01-11 04:59:45
【问题描述】:

我正在从开关数组中解析“switch_name”,但在解析时我得到 nil 值

{
"status": "true",
"result": {
    "hubs": [
        {
            "hub_id": "1",
            "user_id": "35",
            "switch": [
                {
                    "id": "4",
                    "hub_id": "1",
                    "switch_name": "Test2",
                    "user_id": "35",
                    "serial_no": "445112",
                    "topic_sense": "rer",
                    "device_room": "25",
                    "switch_type": "LIGHTS",
                    "types_of_relay_switch": "S"
                }
            ],
            "relay": []
        }
    ],
    "switchwithouhub": []
}

}

我是如何解析的:-

let sName = jsonDict.value(forKeyPath: "result.hubs.switch.switch_name") as? [String]

我在解析 switch_name 时得到 nil 值。 请帮助并建议我如何解析 JSON

【问题讨论】:

  • result.hubs 是一个数组,而不是字典。
  • 我不知道更多关于 keyPath 的使用,但是 hubs 是数组你不需要定义索引或任何东西吗?
  • jsonviewer.stack.hu 见 Json 以正确的格式检查是哪种数据类型并定义数组或字典或单个对象。你肯定会发现不对的地方

标签: ios json swift


【解决方案1】:

您正在尝试直接访问数组(集线器、交换机)的元素。您必须提供正确的索引才能访问该项目。

let sName = jsonDict.value(forKeyPath: "result.hubs[0].switch[0].switch_name") as? String

更新:您可以使用 SwiftyJson 来解析 json 数据。

import SwiftyJSON

do { let jsonData = try JSON(data: response.data) {
  let names = jsonData["hubs"][0]["switch"].array.flatMap({ (switch) -> String in 

  return switch.name
})
}
catch {
  print("Swifty Error")
}

【讨论】:

  • 这仍然不太正确。最终结果是String,而不是[String]
  • 但是,如果 switch 数组中有多个对象,那么我们如何解析数组中的 switch_name
  • 您可以使用 Map 或 Flatmap 来返回名称数组。 let names = result.hubs[0].switch.flatMap({ (item) -> String in return item.name })
  • 我已经更新了我的答案,你可能需要调整一些逻辑,我试图展示你必须解析 json 对象的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多