在使用 Alamofire 在 swift 中解析 JSON 时获取 nil 值



我正在解析交换机阵列中的"switch_name",但在解析时得到零值

{
"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时得到零值。请帮助并建议如何解析 JSON

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

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")
}

最新更新