简体   繁体   English

使用Alamofire快速解析JSON时获得nil值

[英]getting nil value while parsing JSON in swift using Alamofire

i am parsing "switch_name" from switch array but i am getting nil value while parsing我正在解析 switch 数组中的“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": []
}

} }

how i am parsing : -我是如何解析的:-

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

i am getting nil value while parsing switch_name.我在解析 switch_name 时得到 nil 值。 please help and suggest how can i parse JSON请帮助并建议我如何解析 JSON

You are trying to access the element of an arrays (hubs, switch) directly.您正在尝试直接访问数组(集线器、交换机)的元素。 You must provide the proper index to access the item.您必须提供正确的索引才能访问该项目。

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

UPDATE: You can use SwiftyJson for parsing json data.更新:您可以使用 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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM