假设我有这个 JSON:
{
"array": [
33,
{"id": 44, "name": "Jonas"}
]
}
我如何编写一个 swift 4 Codable 结构来反序列化这个 JSON?
struct ArrayStruct : Codable {
// What do I put here?
}
最佳答案
您的 JSON 包含一个小错误(array
后缺少一个冒号)。您可以将数组的元素声明为具有关联值的枚举:
let jsonData = """
{
"array": [
33,
{"id": 44, "name": "Jonas"}
]
}
""".data(using: .utf8)!
enum ArrayValue: Decodable {
case int(Int)
case person(Person)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Int.self) {
self = .int(value)
} else if let value = try? container.decode(Person.self) {
self = .person(value)
} else {
let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: "Unknown type")
throw DecodingError.dataCorrupted(context)
}
}
}
struct Person: Decodable {
var id: Int
var name: String
}
struct ArrayStruct: Decodable {
var array: [ArrayValue]
}
let temp = try JSONDecoder().decode(ArrayStruct.self, from: jsonData)
print(temp.array)
(上面的代码只显示了Decodable
,因为这可能是你大部分时间需要的。但是Encodable
遵循类似的想法)
关于json - 具有对象和整数的 Swift 4 可编码数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47383248/