Swift 4.1解析部分JSON

时间:2018-06-27 21:23:15

标签: json swift parsing decodable

我刚接触Swift,想利用Decodable功能,希望能有所帮助。

我正在使用的公共API在“ c”键下发出我想要的数据,但是周围有一些元数据。例如:

{
  a: 1,
  b: 2,
  c: [{
      d: 3,
      e: 4
    },
    {
      d: 5,
      e: 6
    }
  ]
}

我已经创建了一个这样的结构:

struct Block: Decodable {
   d: Int?
   e: Int?
}

如上所述,我希望能够将下的数据从{c>尽可能快地(抱歉)解析为[Block]类型,并希望有4.1种方法可以实现。

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

我认为最简单(最迅速)的方法是创建两个结构

struct BlockResponse: Decodable {
  let c: [Block]
}

struct Block: Decodable {
  let d: Int?
  let e: Int?
}

然后

let result = try decoder.decode(BlockResponse.self, from: jsonResponse)

编辑: 您也可以像这里省略BlockResponse https://gist.github.com/sgr-ksmt/d3b79ed1504768f2058c5ea06dc93698

通过在keyPath中使用扩展名:

extension JSONDecoder {
  func decode<T: Decodable>(_ type: T.Type, from data: Data, keyPath: String) throws -> T {
      let toplevel = try JSONSerialization.jsonObject(with: data)
      if let nestedJson = (toplevel as AnyObject).value(forKeyPath: keyPath) {
          let nestedJsonData = try JSONSerialization.data(withJSONObject: nestedJson)
          return try decode(type, from: nestedJsonData)
      } else {
          throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Nested json not found for key path \"\(keyPath)\""))
      }
  }
}



try decoder.decode([Block].self, from: data, keyPath: "c")