忽略 Codable 中的包装键

Ignore wrapping keys in Codable

我得到一个 JSON,看起来像这样:

{
    looks =     (
                {
                     ... look object
        }
    );
    query =     (
        ... array of strings
    );
    slices =     (
                (
                        {
                    ... another object
            }
        )
    );

我使用 [String: [Look]] 作为解码对象,因为我只期待一把钥匙("looks" 一把钥匙),但意外收到了另外两把钥匙。当然,在正确解码第一个包装密钥后,尝试解码 "query" 时会失败,因为内容不是 [Look]

最好的方法是什么?理想情况下,我想要一种足够灵活的方法来处理添加其他顶级包装密钥的情况,而不会在将来导致解码失败。

谢谢!

很难知道你在找什么,因为你发布的不是 JSON,但我想你想要的是这个:

struct Looks {
    let looks: [Look]
}

let looks = try JSONDecoder().decode(Looks.self, from: data).looks

创建一个与您实际收到的密钥匹配的简单容器;然后从那个容器中取出你想要的碎片。

您可以在解码上下文中使用values.decodeIfPresent(Type.self, forKey: .key)

针对您的情况: 创建响应 class,如下所示:

 struct Result: Decodable {
  var look: [Look]
  var query: [String]?
  var slices: [SlicesType]?

 enum ResultKeys: String, CodingKey {
  case look = "look"
  case query = "query"
  case slices = "slices"
 }

 init(from decoder: Decoder) throws {
  let container = try decoder.container(keyedBy: ResultKeys.self)
  self.look = try container.decodeIfPresent(Look.self, forKey: .look)
  self.query = try container.decodeIfPresent([String].self, forKey: .query)
  self.slices = try container.decodeIfPresent([String].self, forKey: .slices)
 }
}

解码时可以使用

  let myStruct = try JSONDecoder().decode(Result.self, from: yourJsonData).

如果结构中的变量名与 json 中的键名相同,则不必创建 CodingKeys。

这样即使缺少任何一个键也不会中断执行

希望对您有所帮助!!!