【问题标题】:Is there a way to ignore certain keys with Decodable just extract their values?有没有办法用 Decodable 忽略某些键,只提取它们的值?
【发布时间】: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


【解决方案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)

【讨论】:

  • 谢谢!我确定我之前尝试过这个建议,但由于某种原因它现在可以工作了。非常感谢您的帮助。
猜你喜欢
  • 2022-06-22
  • 2010-11-19
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多