使用 Swift 4 的 Codable 进行类型转换

Type conversion with Swift 4's Codable

我正在 Swift 中使用新的 Codable 协议 4. 我正在通过 [=15= 从网络 API 中提取 JSON 数据].这是一些示例数据:

{
  "image_id": 1,
  "resolutions": ["1920x1200", "1920x1080"]
}

我想将其解码成这样的结构:

struct Resolution: Codable {
  let x: Int
  let y: Int
}

struct Image: Codable {
  let image_id: Int
  let resolutions: Array<Resolution>
}

但我不确定如何将原始数据中的解析字符串转换为 Resolution 结构中单独的 Int 属性。我读过 official documentation and one or two good tutorials, but these focus on cases where the data can be decoded directly, without any intermediate processing (whereas I need to split the string at the x, convert the results to Ints and assign them to Resolution.x and .y). This 似乎也相关,但提问者希望避免手动解码,而我对这种策略持开放态度(尽管我自己不确定如何去做)。

我的解码步骤是这样的:

let image = try JSONDecoder().decode(Image.self, from data)

其中 dataURLSession.shared.dataTask(with: URL, completionHandler: Data?, URLResponse?, Error?) -> Void)

提供

对于每个 Resolution,您想要解码单个字符串,然后将其解析为两个 Int 组件。要解码单个值,您希望在 init(from:) 的实现中从 decoder 获取 singleValueContainer(),然后对其调用 .decode(String.self)

如果您 运行 转换为格式不正确的字符串,则可以使用 components(separatedBy:) in order to get the components, and then Int's string initialiser to convert those to integers, throwing a DecodingError.dataCorruptedError

编码更简单,因为您只需使用字符串插值即可将字符串编码到单个值容器中。

例如:

import Foundation

struct Resolution {
  let width: Int
  let height: Int
}

extension Resolution : Codable {
  init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()

    let resolutionString = try container.decode(String.self)
    let resolutionComponents = resolutionString.components(separatedBy: "x")

    guard resolutionComponents.count == 2,
      let width = Int(resolutionComponents[0]),
      let height = Int(resolutionComponents[1])
      else {
        throw DecodingError.dataCorruptedError(in: container, debugDescription:
          """
          Incorrectly formatted resolution string "\(resolutionString)". \
          It must be in the form <width>x<height>, where width and height are \
          representable as Ints
          """
        )
      }

    self.width = width
    self.height = height
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    try container.encode("\(width)x\(height)")
  }
}

然后你可以像这样使用它:

struct Image : Codable {

    let imageID: Int
    let resolutions: [Resolution]

    private enum CodingKeys : String, CodingKey {
        case imageID = "image_id", resolutions
    }
}

let jsonData = """
{
  "image_id": 1,
  "resolutions": ["1920x1200", "1920x1080"]
}
""".data(using: .utf8)!

do {
    let image = try JSONDecoder().decode(Image.self, from: jsonData)
    print(image)
} catch {
    print(error)
}

// Image(imageID: 1, resolutions: [
//                                  Resolution(width: 1920, height: 1200),
//                                  Resolution(width: 1920, height: 1080)
//                                ]
// )

请注意,我们在 Image 中使用了 ,因此我们可以为 imageID 使用驼峰式 属性 名称,但要指定 JSON 对象键是 image_id.