gpt4 book ai didi

json - OpenWeatherMap 和 Swift 4

转载 作者:行者123 更新时间:2023-11-30 10:58:23 57 4
gpt4 key购买 nike

我正在尝试使用 Swift 4 中的 OpenWeatherMap API 构建一个简单的天气应用程序。我可以在简单的情况下解析 Json 数据,但是这个结构更复杂。

这是 API 返回的 Json 文件。

{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":520,"main":"Rain","description":"light intensity shower rain","icon":"09n"}],"base":"stations","main":{"temp":288.82,"pressure":1019,"humidity":100,"temp_min":288.15,"temp_max":289.15},"visibility":10000,"wind":{"speed":4.1,"deg":200},"clouds":{"all":90},"dt":1544284800,"sys":{"type":1,"id":9548,"message":0.5221,"country":"AU","sunrise":1544208677,"sunset":1544261597},"id":2158177,"name":"Melbourne","cod":200}

我创建了一些结构来获取 Json 数据。

struct CurrentLocalWeather: Decodable {
let base: String
let clouds: Clouds
let cod: Int
let coord: Coord
let dt: Int
let id: Int
let main: Main
let name: String
let sys: Sys
let visibility: Int
let weather: [Weather]
let wind: Wind
}
struct Clouds: Decodable {
let all: Int
}
struct Coord: Decodable {
let lat: Double
let lon: Double
}
struct Main: Decodable {
let humidity: Int
let pressure: Int
let temp: Double
let tempMax: Int
let tempMin: Int
private enum CodingKeys: String, CodingKey {
case humidity, pressure, temp, tempMax = "temp_max", tempMin = "temp_min"
}
}
struct Sys: Decodable {
let country: String
let id: Int
let message: Double
let sunrise: UInt64
let sunset: UInt64
let type: Int
}
struct Weather: Decodable {
let description: String
let icon: String
let id: Int
let main: String
}
struct Wind: Decodable {
let deg: Int
let speed: Double
}

要使用这些数据,这是我编写的代码:

let url = "https://api.openweathermap.org/data/2.5/weather?q=melbourne&APPID=XXXXXXXXXXXXXXXX"
let objurl = URL(string: url)

URLSession.shared.dataTask(with: objurl!) {(data, response, error) in

do {
let forecast = try JSONDecoder().decode([CurrentLocalWeather].self, from: data!)
for weather in forecast {
print(weather.name)
}
} catch {
print("Error")
}

}.resume()

这应该在控制台中打印城市名称。不幸的是它打印错误。

最佳答案

你需要

let forecast = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
print(forcast.name)

因为根是字典而不是数组

关于json - OpenWeatherMap 和 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687617/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com