如何在不使用Codable协议的密钥的情况下解码JSON字典

时间:2019-08-28 14:19:22

标签: json swift api codable

假设我收到了Weather 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
      }
   }
}

我的Result数据类型包含一个温度属性,该属性可以包含地面对象中的任何JSON字典

struct Result: Codable {
    let ????: [String: Any]

}

struct Temperature: Codable {
    let ground: Int
}

有人知道如何使用Codable协议来实现此目的,以正确解析每个forcast,而无需使用其密钥吗?

2 个答案:

答案 0 :(得分:2)

为压力,温度和封闭对象创建结构

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: ...)

字典键代表日期

答案 1 :(得分:1)

您可以使用此网站https://app.quicktype.io

从JSON生成模型和序列化器。
  

天气价值

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
   }
}
  

Typealias

public typealias Weather = [String: WeatherValue]
  

解码

let weather = try? newJSONDecoder().decode(Weather.self, from: jsonData)