I'm having trouble to decode a simple JSON api result using structs.
This is the JSON stucture (part of it):
{
"ad": "Andorra",
"ae": "United Arab Emirates",
"af": "Afghanistan",
"ag": "Antigua and Barbuda",
"ai": "Anguilla",
"al": "Albania"
}
This are the structs I created:
struct Countries: Codable {
var countries: [Country]
}
struct Country: Codable, Identifiable {
var id = UUID()
var code: String
var name: String
}
And using an API I am doing this to try to decode it:
let decodedResponse = try JSONDecoder().decode(Countries.self, from: data)
At the moment this is the error:
No value associated with key CodingKeys(stringValue: "countries", intValue: nil) ("countries").
As I understand correctly the JSON result has two things, the keys and the values. The keys in this case are the country codes (two letters) and the values are the country names. I do want to use both of them in my app but I struggle to use both the key and value using a struct. The error at the moment is also because the dictionary itself has no key. But I can also imagine the values in a single Country will also not work.
[String:String]and then manually transform the data into your desired data structure manually by looping over the dictionary.let decodedResponse = try JSONDecoder().decode([String: String].self, from: data) DispatchQueue.main.async() { for item in decodedResponse { countries.append(Country(code: item.key, name: item.value)) } }And print(countries) results in:Countries.Country(code: "ar", name: "Argentina"), Countries.Country(code: "gu", name: "Guam"), etcBut its not showing any in my list:ForEach(countries, id:\.self) { country in Text(country.name) }