Swift 4.1 JSON 的解析部分

Swift 4.1 Parse Portion of JSON

我刚接触 Swift,想利用 Decodable 功能,希望得到一些帮助。

A public API I am consuming 在密钥下发出我想要的数据:'c' 但周围有一些元数据。例如:

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

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

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

如上所述,我希望能够将数据解析为类型:[Block] 来自 'c' 下的数据 swiftly (抱歉)并希望有一个 4.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")