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

标签 json swift swift4 codable

我正在使用 Swift 4 中的新 Codable 协议(protocol)。我正在通过 URLSession 从 Web 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和一两个好tutorials ,但这些集中在数据可以直接解码的情况下,无需任何中间处理(而我需要在 x 处拆分字符串,将结果转换为 Int并将它们分配给 Resolution.x.y)。这question似乎也相关,但提问者希望避免手动解码,而我对这种策略持开放态度(尽管我自己不确定如何去做)。

我的解码步骤是这样的:

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

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

最佳答案

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

然后您可以使用 components(separatedBy:)为了得到组件,然后是Intstring initialiser将它们转换为整数,抛出 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)
//                                ]
// )

注意我们有 defined a custom nested CodingKeys typeImage 中,因此我们可以为 imageID 设置驼峰式属性名称,但指定 JSON 对象键为 image_id

关于json - 使用 Swift 4 的 Codable 进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45080415/

相关文章:

json - 如何使用Json.NET在PowerShell中解析json?

c# - 将 json twitter 字符串反序列化为对象

ios - 是否 URLSession.dataTask(与 :completionHandler:) always call completionHandler only once?

swift - 私有(private)集类及其方法 Swift 4

ios - 使用建议栏快速获取键盘尺寸

json - jquery 1.9 .ajax() 数据类型默认更改?

javascript - 重命名嵌套 JSON 数据集不同级别的变量

ios - 如何在 imagePickerController 委托(delegate)方法中使用五个按钮和五个图像选择

video - Swift Get Video Frame 使用 AVFoundation

swift - RxCocoa 在 Swift4 中映射可选错误,字符串为 'Cannot convert value of type '?