提问人:Andy 提问时间:3/17/2023 最后编辑:Dávid PásztorAndy 更新时间:3/17/2023 访问量:65
根据 API 文档,从响应中解析数据的结构应该是什么?
What are structs should be according to API docs to parse data from response?
问:
我需要结构来解码地表风数据。
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]
}
此外,我还需要结构来解码地表风的数据。
答:
-1赞
workingdog support Ukraine
3/17/2023
#1
您可以尝试使用动态键的这种方法,在我的测试中有效:
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
}
}
}
}
评论
units
[String: String]
{parameter-level}: float[],
let parameterLevelName: [Float],