将字典解码为可编码结构数组



我有JSON作为字典[字符串,任何对象]:

{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
}

我需要将其解码为可编码结构数组 货币,例如:

struct Currency: Codable {
var code: String
var name: String
}
Currency(code: "AED", name: "United Arab Emirates Dirham")

您可以将 json 解码为 Dictionary 并映射到 Array。

let currencies = try? JSONDecoder()
.decode([String: String].self, from: data)
.map({ Currency(code: $0.key, name: $0.value) })

您需要创建一个容器,例如名为"货币"才能使用单值容器。

我给你分享一个示例游乐场:

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)

相关内容

  • 没有找到相关文章

最新更新