有没有办法用 Decodable 忽略某些键,只是提取它们的值?
Is there a way to ignore certain keys with Decodable just extract their values?
我有以下 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
并解码 [String: [Garten]].self
。然后获取与 "str"
键关联的值:
let attrsDict = try! decoder.decode([String: [Garten]].self, from: json)
let attrs = attrsDict["str"]!
您可以将其包装在一个函数中:
func decodeNestedObject<T: Codable>(_ type: T.Type, key: String,
from data: Data, using decoder: JSONDecoder = JSONDecoder()) throws -> T {
try decoder.decode([String: T].self, from: data)[key]!
}
用法:
let attrs = try decodeNestedObject([Garten].self, key: "str", from: data)
我有以下 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
并解码 [String: [Garten]].self
。然后获取与 "str"
键关联的值:
let attrsDict = try! decoder.decode([String: [Garten]].self, from: json)
let attrs = attrsDict["str"]!
您可以将其包装在一个函数中:
func decodeNestedObject<T: Codable>(_ type: T.Type, key: String,
from data: Data, using decoder: JSONDecoder = JSONDecoder()) throws -> T {
try decoder.decode([String: T].self, from: data)[key]!
}
用法:
let attrs = try decodeNestedObject([Garten].self, key: "str", from: data)