对于 each Resolution
,您想要解码单个字符串,然后将其解析为两个Int
组件。要解码单个值,您希望singleValueContainer()
从 的decoder
实现中获取 a init(from:)
,然后调用.decode(String.self)
它。
然后,您可以使用components(separatedBy:)
in order 获取组件,然后使用Int
's字符串初始化DecodingError.dataCorruptedError
程序将它们转换为整数,如果遇到格式不正确的字符串,则抛出 a 。
编码更简单,因为您可以只使用字符串插值来将字符串编码到单个值容器中。
例如:
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)
// ]
// )
请注意,我们已经定义了一个自定义嵌套CodingKeys
类型,Image
因此我们可以为 提供一个驼峰式属性名称imageID
,但指定 JSON 对象键为image_id
。