从NSArray中读出特定的JSON

问题描述 投票:-1回答:1

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

["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"]!

上面的代码工作正常,但我在阅读第一个天气元素(called "light snow")的描述时遇到了大量问题:

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

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

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

提前一百万谢谢。

ios json swift web-applications
1个回答
0
投票

也用这个API :)

这对我有用:

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

更新:如果您希望所有数组元素都遍历weathersArray并获取所有描述。

© www.soinside.com 2019 - 2024. All rights reserved.