简体   繁体   中英

Read out specific JSON from NSArray

This is the JSON object I'm getting from the openweathermap - 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;
}]

Because I like to readout some information (like the current temperature , the weather description , etc.) I tried to use this few lines:

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

The code above is working fine but I got massive problems reading out the description of the first Weather element (called "light snow") :

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

... doesn't seems working at all.

So how can I fix this issue?

Thanks a million in advance.

Also used this API :)

This worked for me:

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

Update: in case you want all the array elements just loop over the weathersArray and get all the descriptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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