简体   繁体   English

如何使用 Codable 处理不同类型的 JSON 数据?

[英]How can I handle different types of JSON data with Codable?

struct Sample: Codable {
    let dataA: Info?

    enum CodingKeys: String, CodingKey {
        case dataA
    }

    enum Info: Codable {
        case double(Double)
        case string(String)

        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(String.self) {
                self = .string(x)
                return
            }
            throw DecodingError.typeMismatch(Info.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Info"))
        }

        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            switch self {
            case .double(let x):
                try container.encode(x)
            case .string(let x):
                try container.encode(x)
            }
        }
    }
}

So, I've got some data from server as JSON and converted for my model "Sample".因此,我从服务器获得了一些数据,如 JSON 并转换为我的 model“样本”。

As you can see, Sample.data can be String or Double .如您所见, Sample.data可以是StringDouble

But I don't know how I can get dataA in other class.但我不知道如何在其他dataA中获取 dataA。

let foodRate = dataFromServer.dataA .....? let foodRate = dataFromServer.dataA .....?

What should I do for using dataA ?使用dataA应该怎么做?

You can use a switch statement to extract the values您可以使用switch语句来提取值

switch dataFromServer.dataA {
case .double(let number):
    print(number)
case .string(let string):
    print(string)
case .none:
    print("Empty")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM