当 api 在 {} 而不是 [] 中时,如何从中获取内容

How do I grab stuff from the api when it's in {} not []

我正在尝试为一个项目制作天气应用程序,我正在为我的 api 使用 openweathermap。我得到它来输出一些信息,但我不知道如何获取其余信息。这是我把它放入 Postman 时出现的结果。我如何获取 {} 中的信息,例如温度以及最低和最高温度?我知道如果它是一个数组我可以遍历它但它不是。

到目前为止,我已经尝试像数组一样遍历它,但没有成功:

if let mainJson = jsonObject["main"] as? [[String:AnyObject]]
{
    for eachtemp in mainJson
    {
        if let temp = eachtemp["temp"] as? String
        {
            print("the temp is: ", temp)
        }
    }
}

这是来自 api 的回复:

{
    "coord": {
        "lon": -88.75,
        "lat": 41.93
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 281.24,
        "pressure": 1019,
        "humidity": 52,
        "temp_min": 279.26,
        "temp_max": 283.15
    },
    "visibility": 16093,
    "wind": {
        "speed": 7.7,
        "deg": 280,
        "gust": 11.3
    },
    "clouds": {
        "all": 1
    },
    "dt": 1555176309,
    "sys": {
        "type": 1,
        "id": 5706,
        "message": 0.0073,
        "country": "US",
        "sunrise": 1555154275,
        "sunset": 1555201965
    },
    "id": 420012399,
    "name": "Aurora",
    "cod": 200
}

{}是一个字典(Swift类型[String:Any]never [String:AnyObject]),你必须得到每个值使用密钥订阅,所有请求的值都是 Double

if let main = jsonObject["main"] as? [String:Any] {
    let temp = main["temp"] as! Double
    let tempMin = main["temp_min"] as! Double
    let tempMax = main["temp_max"] as! Double
    print(temp, tempMin, tempMax)
}

关于强制展开:openweathermap 发送非常可靠的数据。如果 main 存在,里面的键也存在


有了Decodable就容易多了

struct WeatherAPI : Decodable {

    let main: Main

    struct Main : Decodable {
        let temp, tempMin, tempMax : Double
    }
}

let apiKey = ....

let url = URL(string:"http://api.openweathermap.org/data/2.5/weather?....." + apiKey)!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error { print(error); return }
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let result = try decoder.decode(WeatherAPI.self, from: data!)
        print(result.main.temp, result.main.tempMin, result.main.tempMax)
    } catch {
        print(error)
    }
}
task.resume()