json 根据API文档,解析响应中的数据应该使用什么结构?

omqzjyyz  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(93)

我需要结构体来解码地表风数据。
https://api.windy.com/point-forecast/docs
API文档的响应正文:

{
    ts:int[],
    units: {
        {parameter-level}: string,
        {parameter2-level}: string,
        ...
    },
    {parameter-level}: float[],
    {parameter2-level}: float[],
    ...

}
仅成功将ts:int[]解码到此结构:

struct Response: Codable {
    var ts: [Int]
}

我还需要结构来解码数据的表面风。

xkrw2x1b

xkrw2x1b1#

您可以尝试这种方法,使用动态键,在我的测试工作:

struct ResponseAPI: Decodable {
    var ts: [Int]
    var units: [String:String]
    var data: [String:[Float]]

    init(ts: [Int], units: [String:String], data: [String:[Float]]) {
       self.ts = ts
       self.units = units
       self.data = data
    }
    
    enum CodingKeys: String, CodingKey {
        case ts, units
    }
    
    struct AnyKey: CodingKey {
        var stringValue: String
        var intValue: Int?
        
        init?(stringValue: String) {  self.stringValue = stringValue  }
        init?(intValue: Int) { return nil } // never used
    }
    
    init(from decoder: Decoder) throws {
        let container1 = try decoder.container(keyedBy: CodingKeys.self)
        self.ts = try container1.decode([Int].self, forKey: .ts)
        self.units = try container1.decode([String:String].self, forKey: .units)
        self.data = [:]
        let container2 = try decoder.container(keyedBy: AnyKey.self)
        container2.allKeys.forEach { key in
            if let theFloats = try? container2.decode([Float].self, forKey: key) {
                self.data[key.stringValue] = theFloats
            }
        }
    }
    
}

相关问题