0

I have the following data model which I am trying to decode JSON from an API into.

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": "success", "lat": 12, "lng": 77, "data": [ { "Count": { "grass_pollen": 51, "tree_pollen": 34, "weed_pollen": 26 }, "Risk": { "grass_pollen": "Moderate", "tree_pollen": "Low", "weed_pollen": "Moderate" }, "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
ArQangel
  • 65
  • 5
  • I may have solved this and it is a cautionary tale if I have it correctly. I was using the decoder.keyDecodingStrategy = .convertFromSnakeCase I think this is applied before the CodingKeys values. So I was looking for "Count" in the JSON which I think had already been converted to "count" and so the codingKeys were throwing up the error. I removed the decoder strategy and it all started to work. – ArQangel Jun 10 '23 at 18:14

0 Answers0