我需要序列化以下类型的 JSON 响应。有不同的类型
[{
"type": "respiration_rate",
"value": 45
}
{ "type": "blood_pressure",
"value": { hg: 50 ,mm:120 }
}]
我序列化上层json的类是
class Template: Codable {
var type: String?
var value: Double?
private enum CodingKeys: String, CodingKey {
case type
case value
}
}
如何序列化 value
是 double 还是动态对象?
最佳答案
这是您需要的代码:
class Template: Codable {
let type: String?
let value: Value?
private enum CodingKeys: String, CodingKey {
case type
case value
}
typealias ValueDictionary = Dictionary<String, Int>
enum Value: Codable {
case double(Double)
case object(ValueDictionary)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Double.self) {
self = .double(x)
return
}
if let x = try? container.decode(ValueDictionary.self) {
self = .object(x)
return
}
throw DecodingError.typeMismatch(Value.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ValueUnion"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .double(let x):
try container.encode(x)
case .object(let x):
try container.encode(x)
}
}
}
}
关于ios - 如何使用动态类型反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125973/