在Swift中使用动态键解析JSON

时间:2016-09-13 07:53:46

标签: ios json swift parsing

我正在尝试从网址解析JSON文件。此JSON具有动态密钥,因为它会更改每个文件。现在我的代码看起来像这样:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)


                // Parsing
                if let stations = json["observations"]!!["-10019482"] as? [[String: AnyObject]] {

                    for observation in stations {

                        if let name = observation["stationname"] as? String {

                            if let temperatuuri = observation["Temperature"] as? String {
                                if let windSpeed = observation["WindSpeedMS"] as? String {
                                    print(name, temperatuuri, windSpeed,"m/s")
                                    self.temperature.text = String(temperatuuri)
                                }
                            }

                        }

                    }
                }

“ - 10019482”是动态更改的部分,无法预测密钥名称。但是,我知道它始终是“观察”中的第一个关键。

我如何做同样的事情,但没有搜索特定的密钥名称?

1 个答案:

答案 0 :(得分:0)

由于json["observations"]是一个字典,你可以做这样的事情来获得它的第一个关键

guard let dict = json["observations"] as? [String: AnyObject],
    let firstKey = dict.keys.first else { return }

print(firstKey) // should print the first key found in the observations dictionary