This does not represent the entire data, I left some work for you ??
Please read the JSON carefully, all dictionaries ({}
) can be decoded into a struct, all values in double quotes are String
, floating point numeric values are Double
, the other Int
, the Int
dates starting with 1523... can be decoded to Date
with the appropriate date strategy:
let jsonString = """
{"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":294.15,"pressure":1012,"humidity":52,"temp_min":294.15,"temp_max":294.15},"visibility":10000,"wind":{"speed":6.7,"deg":90},"clouds":{"all":0},"dt":1523548800,"sys":{"type":1,"id":5374,"message":0.0023,"country":"PL","sunrise":1523504666,"sunset":1523554192},"id":756135,"name":"Warsaw","cod":200}
"""
struct Root : Decodable {
let coord : Coordinate
let weather : [Weather]
let base : String
let main : Main
let dt : Date
}
struct Coordinate : Decodable {
let lat, lon : Double
}
struct Weather : Decodable {
let id : Int
let main, description, icon : String
}
struct Main : Decodable {
let temp, tempMin, tempMax : Double
let pressure, humidity : Int
}
let data = Data(jsonString.utf8)
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
let result = try decoder.decode(Root.self, from: data)
print(result)
} catch { print(error) }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…