ios - 如何使用动态类型反序列化 JSON

标签 ios json swift object serialization

我需要序列化以下类型的 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/

相关文章:

java - 如何在Java中将JsonArray从JsonArray格式的字符串转换为JsonArray?

php - Instagram API - 仅检索视频

javascript - 处理 JSON 创建一个普通数组而不是 JSON 对象

ios - objc_exception_throw 异常与 AVCapturePhotoOutput capturePhotoWithSettings 方法

ios - 枚举数组和枚举字典之间的映射

ios - 多个NSDate范围的求和区间

swift - 为什么实例成员 'getPerson' 不能用于类型 'GetPerson'

ios - UITableViewAutomaticDimension 在滚动之前不工作

ios - 为所有页面添加导航栏和标签栏

ios - 如果没有互联网,防止应用程序崩溃