繁体   English   中英

从 NSArray 读出特定的 JSON

[英]Read out specific JSON from NSArray

这是我从 openweathermap - API 得到的 JSON 对象:

["main": {
    humidity = 12;
    pressure = 922;
    temp = "271.13";
    "temp_max" = "171.15";
    "temp_min" = "291.15";
}, "name": mycity, "id": 299129219, "coord": {
    lat = "92.1211";
    lon = "182.1211";
}, "weather": <__NSArrayI 0x1c042e820>(
{
    description = "light snow";
    icon = 13n;
    id = 120;
    main = Snow;
},
{
    description = mist;
    icon = 50n;
    id = 722;
    main = Mist;
}
)
, "clouds": {
    all = 12;
}, "dt": 211, "base": stations, "sys": {
    country = XXX;
    id = 4891;
    message = "0.02221";
    sunrise = 1221122112;
    sunset = 4343344343;
    type = 1;
}, "cod": 100, "visibility": 3200, "wind": {
    speed = 3;
}]

因为我喜欢读出一些信息(比如当前温度天气描述等)我尝试使用这几行:

let temperature = (result["main"] as! [String:Double])["temp"]!

上面的代码运行良好,但我在读取第一个 Weather 元素(called "light snow")的描述时遇到了很多问题:

let description = (result["weather"] as! [String:Any]).first["description"]! //(result should be : "light snow")

......似乎根本不起作用。

那么我该如何解决这个问题呢?

预先感谢一百万。

也用过这个 API :)

这对我有用:

guard let weathersArray = json["weather"] as? [[String: Any]],
        let weatherJson = weathersArray.first,
        let description = weatherJson["description"] as? String
        else { return }

更新:如果您想要所有数组元素,只需遍历weathersArray 并获取所有描述。

暂无
暂无

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

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