0

I am trying to decode this json which is available via a URL.

{
    "40260005": {
        "postalcode": "40260",
        "name": "CASTETS",
        "brand": "BLAH"
    },
    "40180001": {
        "postalcode": "40180",
        "name": "NONAME",
        "brand": "NONE"
    }
}

I understand that is a JSON dictionary.

I would like to decode to an array of objects (if this is possible)

My model looks like this:

struct FullBrandsList: Codable, Hashable {
    let postalcode, name: String
    let brand: String
}

I am using this for decoding, but I am always getting the below error.

let decoder = JSONDecoder()
                    
do {
                        
    let dataResponse = try decoder.decode(FullBrandsList.self, from: data)
                        
    completion(Result.success(dataResponse))
                        
}

KeyNotFound(CodingKeys(stringValue: "postalcode", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "postalcode", intValue: nil) ("postalcode").", underlyingError: nil))

I suspect that my model struct is incorrect but can't work out how. Any ideas ?

Thanks

vicegax
  • 4,709
  • 28
  • 37
jat
  • 183
  • 3
  • 14
  • `decoder.decode([String: FullBrandsList].self, ...` to decode as a dictionary and then you can access the `value` property of the dictionary to get the array – Joakim Danielson Oct 14 '22 at 14:04

0 Answers0