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

问题描述 投票:0回答:1
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)
            }
        }
    }
}

所以,我从服务器上得到了一些JSON数据,并为我的模型 "Sample "进行了转换。

如你所见。Sample.data 可以 StringDouble.

但我不知道如何才能得到。dataA 在其他班级。

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

我应该如何使用 dataA?

json swift codable decodable
1个回答
0
投票

你可以使用 switch 语句来提取值

switch dataFromServer.dataA {
case .double(let number):
    print(number)
case .string(let string):
    print(string)
case .none:
    print("Empty")
}
© www.soinside.com 2019 - 2024. All rights reserved.