使用 SWIFT CodingKeys 错误解码 JSON

Decoding JSON with SWIFT CodingKeys Error

提问人:ArQangel 提问时间:6/11/2023 更新时间:6/11/2023 访问量:12

问:

我有以下数据模型,我正在尝试将 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
json swift3 jsondecoder swift-structs

评论

0赞 ArQangel 6/11/2023
我可能已经解决了这个问题,如果我没看错的话,这是一个警示故事。我使用的是 decoder.keyDecodingStrategy = .convertFromSnakeCase,我认为这在 CodingKeys 值之前应用。所以我在JSON中寻找“Count”,我认为它已经转换为“count”,所以codingKeys抛出了错误。我删除了解码器策略,一切都开始起作用了。😕

答: 暂无答案