如何使用 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)
}
}
}
}
所以,我从服务器获取了一些数据作为 JSON 并针对我的模型进行了转换 "Sample"。
如您所见,Sample.data
可以是String
或Double
。
但我不知道如何在其他 class 中获得 dataA
。
let foodRate = dataFromServer.dataA
.......?
使用dataA
我应该做什么?
您可以使用 switch
语句来提取值
switch dataFromServer.dataA {
case .double(let number):
print(number)
case .string(let string):
print(string)
case .none:
print("Empty")
}
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
可以是String
或Double
。
但我不知道如何在其他 class 中获得 dataA
。
let foodRate = dataFromServer.dataA
.......?
使用dataA
我应该做什么?
您可以使用 switch
语句来提取值
switch dataFromServer.dataA {
case .double(let number):
print(number)
case .string(let string):
print(string)
case .none:
print("Empty")
}