【问题标题】:How to decode a JSON dictionary without using its key with Codable protocol [closed]如何在不使用 Codable 协议的密钥的情况下解码 JSON 字典 [关闭]
【发布时间】:2019-08-28 14:19:22
【问题描述】:

假设我收到了来自 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 协议来实现这一点,以便在不使用其密钥的情况下正确解析每个预测?

【问题讨论】:

    标签: json swift api codable


    【解决方案1】:

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

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

    字典键代表日期

    【讨论】:

    • 无法读取数据,因为它的格式不正确。
    • 我的错,这是see_level,我读到了 sea 级别。我更新了答案。顺便说一句,不要打印localizedDescription,始终打印error 实例以获得更具描述性的错误消息。
    【解决方案2】:

    您可以使用此网站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
       }
    }
    

    类型别名

    public typealias Weather = [String: WeatherValue]
    

    解码

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

    【讨论】:

    • 非常有帮助,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多