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

时间:2018-09-01 07:33:55

标签: 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或动态对象?

2 个答案:

答案 0 :(得分:1)

这是您需要的代码:

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)
            }
        }
    }
}

答案 1 :(得分:0)

您可以使用带有关联值的枚举而不是类,因为JSON格式似乎是异构的。

enum Value: Decodable {
    case respirationRate(Double)
    case bloodPressure(hg: Double, mm: Double)

    private struct BloodPresure: Decodable {
        let hg: Double
        let mm: Double
    }

    private enum CodingKeys: String, CodingKey {
        case type
        case value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        switch try container.decode(String.self, forKey: .type) {
        case "respiration_rate":
            self = try .respirationRate(container.decode(Double.self, forKey: .value))
        case "blood_pressure":
            let details = try container.decode(BloodPresure.self, forKey: .value)
            self = .bloodPressure(hg: details.hg, mm: details.mm)
        case let type: throw DecodingError.dataCorruptedError(forKey: .value, in: container, debugDescription: "Invalid type: \(type)")
        }
    }
}

现在轻松解码json:

let json = """
[{
"type": "respiration_rate",
"value": 45
},
{ "type": "blood_pressure",
"value": { "hg": 50 ,"mm":120 }
}]
"""

do {
    let values = try JSONDecoder().decode([Value].self, from: json.data(using: .utf8)!)
    print(values)
} catch {
    print(error)
}