提问人:ArQangel 提问时间:6/11/2023 更新时间:6/11/2023 访问量:12
使用 SWIFT CodingKeys 错误解码 JSON
Decoding JSON with SWIFT CodingKeys Error
问:
我有以下数据模型,我正在尝试将 JSON 从 API 解码到其中。
struct Data: Identifiable, Codable {
var id = UUID()
let count: Count
let risk: Risk
let updatedAt: String
enum CodingKeys: String, CodingKey {
case count = "Count"
case risk = "Risk"
case updatedAt
}
}
struct Count: Codable {
let grassPollen: Int
let treePollen: Int
let weedPollen: Int
enum CodingKeys: String, CodingKey {
case grassPollen = "grass_pollen"
case treePollen = "tree_pollen"
case weedPollen = "weed_pollen"
}
}
struct Risk: Codable {
let grassPollen: String
let treePollen: String
let weedPollen: String
enum CodingKeys: String, CodingKey {
case grassPollen = "grass_pollen"
case treePollen = "tree_pollen"
case weedPollen = "weed_pollen"
}
}
The JSON data I am tring to decode into the structure is as follows.
{ “message”: “成功”, “纬度”:12, “液化天然气”:77, “数据”:[ { “计数”:{ “grass_pollen”:51, “tree_pollen”:34, “weed_pollen”:26 }, “风险”:{ “grass_pollen”: “中等”, “tree_pollen”: “低”, “weed_pollen”: “中等” }, “updatedAt”: “2023-06-10T13:57:17.000Z” } ] }
I am getting the following error when the decode takes place.
>
> keyNotFound(CodingKeys(stringValue: "count", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"count\", intValue: nil) (\"count\").", underlyingError: nil))
>
I know the model has to have the same names etc. But I have been looking at this for ages and can't see what is wrong. I am just learning swift and am definitely a novice with JSON.
So am I doing or missing something stupid?
I have tried various versions of renaming the code and taking the COdingKeys out completely. If I change the coding key "Count" to something else it reflects that in the decode error, but despite trying various options. I'm stuck
答: 暂无答案
评论