Reputation: 93
I have JSON as dictionary [String, Anyobject]:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
}
I need to decode it as array of codable structs Currency like:
struct Currency: Codable {
var code: String
var name: String
}
Currency(code: "AED", name: "United Arab Emirates Dirham")
Upvotes: 0
Views: 139
Reputation: 4097
You need to create a container, for example named "Currencies" to use the single value container.
I share you the example playground:
let str = """
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
}
"""
struct Currencies: Codable {
var values: [Currency]
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let dict = try container.decode([String: String].self)
values = dict.map({ (key, value) in
return Currency(code: key, name: value)
})
}
}
struct Currency: Codable {
var code: String
var name: String
enum CodingKeys: String, CodingKey {
case code
case name
}
}
let currencies = try JSONDecoder().decode(Currencies.self, from: Data(str.utf8))
print(currencies.values)
Upvotes: 1
Reputation: 1852
You can decode the json as Dictionary and map to Array.
let currencies = try? JSONDecoder()
.decode([String: String].self, from: data)
.map({ Currency(code: $0.key, name: $0.value) })
Upvotes: 3