【发布时间】:2020-11-01 13:48:55
【问题描述】:
我有以下 JSON 示例
let json = """
{
"str": [
{
"abv": "4.4",
"weight": "4.1",
"volume": "5.0"
}
]
}
""".data(using: .utf8)!
还有以下Decoable 结构体
struct Outer: Decodable {
let stri: [Garten]
enum CodingKeys: String, CodingKey {
case stri = "str"
}
struct Garten: Decodable {
let alcoholByVol: String
let weight: String
let vol: String
enum CodingKeys: String, CodingKey {
case alcoholByVol = "abv"
case weight = "weight"
case vol = "volume"
}
}
}
我想知道是否有任何方法可以避免外部struct。它基本上只存在于解码内部数组的那个键。
这就是我目前的解码方式
let attrs = try! decoder.decode(Outer.self, from: json)
但我很好奇是否有类似的东西
let attrs = try! decoder.decode([[String: [Outer]].self, from: json)
【问题讨论】:
-
是的,你可以,但有一个 [ 太多了
-
您还需要将
Outer替换为Outer.Garten,例如:let attrs = try! decoder.decode([String: [Outer.Garten]].self, from: json)
标签: ios json swift codable decodable