我正在尝试使用Swift 4中的OpenWeatherMap app构建一个简单的天气应用程序,我可以在简单的情况下解析Json数据,但这个应用程序的结构更加复杂。
这是API返回的Json文件。
{“龙”:144.96,“拉”:-37.81},“天气”:{“id”:520,“主”:“雨”,“描述”:“小雨”,“图标”:“09”},“基地”:“台站”,“主”:{“温度”:288.82,“气压”:1019,“湿度”:100,"temp_min":288.15,"temp_max":289.15},“能见度”:10000,“风”:{“速度”:4.1,"deg":200},“云”:{“所有”:90},"dt":1544284800,"sys":{"type":1,"id":9548,"message":0.5221,“AU”,“日出”:1544208677,“日落”:1544261597},"id":2158177,“name”:“墨尔本”,"cod":200}
我创建了一些Struct(s)来获取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()它应该在控制台中打印城市名称。不幸的是它打印错误。
发布于 2018-12-08 22:41:24
你需要
let forecast = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
print(forcast.name)因为根是字典,而不是数组
https://stackoverflow.com/questions/53687617
复制相似问题