0

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")
1
  • I think that the question is fine, I don't know why some people vote negatively. Commented May 27, 2020 at 12:38

2 Answers 2

3

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) })
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.