swift - 当 api 位于 {} 而不是 [] 中时,如何从 api 中获取内容

标签 swift openweathermap

我正在尝试为一个项目制作天气应用程序,并且我正在使用 openweathermap 作为我的 api。我让它输出一些信息,但我不知道如何获取其余信息。这就是我把它放入 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]从不 [String:AnyObject]),您必须通过 key 订阅获取每个值,所有请求的值都是 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()

关于swift - 当 api 位于 {} 而不是 [] 中时,如何从 api 中获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668403/

相关文章:

javascript - 如何在 AngularJs 中将参数从 Controller 传递到服务

ios - Swift - 如何获取 OpenWeatherMap JSON 数据?

javascript - 为什么我的 JavaScript 函数没有触发?

ios - 无法在子类 UITextField 中设置属性占位符的文本颜色

swift - 无法调用 tableView 委托(delegate)和数据源方法

ios - 如何使用 swift 遍历目录中的多个(音频/mp3)文件? - Swift, iOS8 Soundboard AVPlayer

swift - 如何修复被阻挡的 View 过渡到增强现实 View

ios - TableView : how to get a string from selected row?

java - 转换后日出和日落时间相等