可编码/可解码应解码带有字符串的数组



为什么名称数组没有解码?

为游乐场做准备,简单地将其粘贴到您的游乐场中

import Foundation
struct Country : Decodable {
enum CodingKeys : String, CodingKey {
case names
}
var names : [String]?
}
extension Country {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
names = try values.decode([String]?.self, forKey: .names)!
}
}
let json = """
[{
"names":
[
"Andorre",
"Andorra",
"アンドラ"
]
},{
"names":
[
"United Arab Emirates",
"Vereinigte Arabische Emirate",
"Émirats Arabes Unis",
"Emiratos Árabes Unidos",
"アラブ首長国連邦",
"Verenigde Arabische Emiraten"
]
}]
""".data(using: .utf8)!
let decoder = JSONDecoder()
do {
let countries = try decoder.decode([Country].self, from: json)
countries.forEach { print($0) }
} catch {
print("error")
}

您已将names定义为Country可选属性。 如果你的意图是此键可能不存在于 JSON 中 然后使用decodeIfPresent

extension Country {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
names = try values.decodeIfPresent([String].self, forKey: .names)
}
}

如果容器没有与键关联的值,或者值为 null,则此方法返回nil

但实际上您可以省略自定义init(from decoder: Decoder)实现(和enum CodingKeys(,因为这是默认行为,并且将 自动合成。

备注:隐式变量error在任何catch子句中都有定义, 所以

} catch {
print(error.localizedDescription)
}

可以比print("error")提供更多信息(尽管不是 在这种特殊情况下(。

最新更新