使用Codable解析JSON对象数组,但跳过损坏的元素

时间:2018-09-04 21:46:23

标签: json swift parsing codable

我从JSON传递了一堆对象,但结果发现其中一些对象具有空字符串而不是URL。我的模型期望一个有效的URL,我宁愿跳过不合格的对象,也不愿将URL属性设为可选。

事实并非如此简单。是否有内置的方法可以从数组中跳过不可分解的对象?

1 个答案:

答案 0 :(得分:1)

事实证明,这是a ticket in Swift的未解决问题。

我通过以下方式实现了针对问题的解决方法:

struct AnyCodable: Codable {}

struct Trending: Codable {
  var data: [Gif]

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    var gifContainer = try container.nestedUnkeyedContainer(forKey: .data)

    var gifs = [Gif]()

    while !gifContainer.isAtEnd {
      if let gif = try? gifContainer.decode(Gif.self) {
        gifs.append(gif)
      } else {
        let skipped = try? gifContainer.decode(AnyCodable.self)
        print("Skipping one \(skipped)")
      }
    }

    self.data = gifs
  }
}