假设我有一个来自天气API的响应。
{
"2019-08-27 19:00:00":{
"temperature":{
"ground":292,
},
"pressure":{
"see_level":101660
}
},
"2019-08-27 23:00:00":{
"temperature":{
"ground":292,
},
"pressure":{
"see_level":101660
}
}
}
我有一个结果数据类型,其中包含一个温度属性,该属性可以在地面对象中包含任何 JSON 字典
struct Result: Codable {
let ????: [String: Any]
}
struct Temperature: Codable {
let ground: Int
}
有谁知道如何使用 Codable 协议来实现这一点,以便在不使用其密钥的情况下正确解析每个 forcast?
为压力、温度和封闭对象创建结构
struct Pressure: Decodable {
let see_level: Int
}
struct Temperature: Decodable {
let ground: Int
}
struct WeatherData: Decodable {
let pressure : Pressure
let temperature : Temperature
}
然后解码字典
JSONDecoder().decode([String:WeatherData].self, from: ...)
字典键表示日期
您可以使用此网站从 JSON 生成模型和序列化程序 https://app.quicktype.io
天气值
public struct WeatherValue: Codable {
public let temperature: Temperature
public let pressure: Pressure
enum CodingKeys: String, CodingKey {
case temperature
case pressure
}
public init(temperature: Temperature, pressure: Pressure) {
self.temperature = temperature
self.pressure = pressure
}
}
压力
public struct Pressure: Codable {
public let seeLevel: Int
enum CodingKeys: String, CodingKey {
case seeLevel = "see_level"
}
public init(seeLevel: Int) {
self.seeLevel = seeLevel
}
}
温度
public struct Temperature: Codable {
public let ground: Int
enum CodingKeys: String, CodingKey {
case ground
}
public init(ground: Int) {
self.ground = ground
}
}
类型别名
public typealias Weather = [String: WeatherValue]
解码
let weather = try? newJSONDecoder().decode(Weather.self, from: jsonData)