gpt4 book ai didi

ios - 使用 struct decodable swift 在 IOS 中解码具有不同数据类型的 json 数组数据 4/5

转载 作者:行者123 更新时间:2023-11-28 19:25:13 25 4
gpt4 key购买 nike

我已经尝试构建结构并使用它进行解码,但只有当所有数据类型都与定义的相同时它才有效

例如下面的代码工作正常:

{"key1": "stringValue", "key2": intValue, "key3": ["stringData1", "stringData2", "stringData3"]}
struct User: Decodable               
{
var key1: String
var key2: Int
var key3: [String]
}

let decoder = JSONDecoder()
let decodedJsonData = try decoder.decode(User.self, from: data)
print(decodedJsonData)

如果key3包含不同的数据类型,应该如何解码?

{"key1": "stringValue", "key2": intValue, "key3": ["stringData1", IntData, FloatData]}

最佳答案

使用具有关联值的枚举:

struct User: Codable {
let command, updated: Int
let data: [Datum]
}

enum Datum: 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(Datum.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Datum"))
}

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

要获取 data 中的各个值,请使用如下代码:

let json = """
{"command": 1, "updated": 2, "data": ["stringData1", 42, 43]}
""".data(using: .utf8)

do {
let user = try JSONDecoder().decode(User.self, from: json!)

for d in user.data {
switch d {
case .string(let str): print("String value: \(str)")
case .double(let dbl): print("Double value: \(dbl)")
}
}
} catch {
print(error)
}

关于ios - 使用 struct decodable swift 在 IOS 中解码具有不同数据类型的 json 数组数据 4/5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59433734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com