数组中字典的抓取值

时间:2019-04-13 23:03:35

标签: ios swift openweathermap

我正在尝试从数组中的字典中获取一些值,但我不知道该怎么做。我能够从字典和数组中获取内容,但无法将它们组合在一起。如果有帮助,我正在使用openweathermap每小时的api。

我尝试将已经完成的2种不同方式组合在一起,但是那没有用。这是我尝试过的:

struct HourlyWeatherAPI: Decoder
{
    let main: Main
    let wind: Wind
    struct Main: Decodable
    {
        let temp: Double
    }
    struct Wind: Decodable
    {
        let speed, deg: Double
    }
}

那个-^在我的代码的顶部,然后又晚了

if let tempJson = jsonObject["list"] as? [[String:AnyObject]]
{
    for eachTemp in tempJson
    {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let result = try decoder.decode(HourlyWeatherAPI.Main.self, from: data!)
        print(result.temp)
    }
}

这是API的一部分,只是第一个条目。我正在尝试获取main中的内容:

{
    "cod": "200",
    "message": 0.0197,
    "cnt": 96,
    "list": [
        {
            "dt": 1555196400,
            "main": {
                "temp": 282.26,
                "temp_min": 281.409,
                "temp_max": 282.26,
                "pressure": 1018.06,
                "sea_level": 1018.06,
                "grnd_level": 985.672,
                "humidity": 56,
                "temp_kf": 0.85
            },
            "weather": [
                {
                    "id": 804,
                    "main": "Clouds",
                    "description": "overcast clouds",
                    "icon": "04d"
                }
            ],
            "clouds": {
                "all": 100
            },
            "wind": {
                "speed": 3.99,
                "deg": 313.922
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2019-04-13 23:00:00"
        },

1 个答案:

答案 0 :(得分:1)

您希望数据结构从根级别对象开始,以匹配要接收的JSON。然后,您可以解码根对象并访问其中包含的数据结构。

struct Root: Decodable {
     let list:[HourlyWeatherAPI]
}

struct HourlyWeatherAPI: Decodable {
     let main: Main
     let wind: Wind
}

struct Main: Decodable {
    let temp: Double
}

struct Wind: Decodable {
    let speed, deg: Double
}

/* 
 * decode your JSON as before, but use the new Root object as the type. You
 * can then access the hourly weather data from the list property
 */
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data!)
let hourlyWeatherList = result.list
let firstWeatherItem = hourlyWeatherList[0]
let temp = firstWeatherItem.main.temp