有没有一种方法可以忽略仅可解码的某些键而仅提取其值?

时间:2020-11-01 13:48:55

标签: ios json swift codable decodable

我有以下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)

1 个答案:

答案 0 :(得分:1)

您可以完全删除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)