我正在使用 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)
data
由 URLSession.shared.dataTask(with: URL, completionHandler: Data?, URLResponse?, Error?) -> Void) 提供
最佳答案
对于每个 Resolution
,您想要解码单个字符串,然后将其解析为两个 Int
组件。要解码单个值,您需要获得 singleValueContainer()
从init(from:)
的实现中的decoder
,然后在其上调用.decode(String.self)
。
然后您可以使用 components(separatedBy:)
为了得到组件,然后是Int
的string 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
type在 Image
中,因此我们可以为 imageID
设置驼峰式属性名称,但指定 JSON 对象键为 image_id
。
关于json - 使用 Swift 4 的 Codable 进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45080415/