gpt4 book ai didi

Swift Decodable,Endpoint返回完全不同的类型

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

对于我正在使用的 API,我有一种情况,其中 1 个 API 端点可以根据调用是否成功返回完全不同的响应。
如果成功,API 端点会在根目录中返回请求对象的数组,如下所示:

[
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
...
]

我通常用 try JSONDecoder().decode([Object].self, from: data) 解码

如果发生错误,API 端点会返回完全不同的内容,如下所示:

{
"error": "value1",
"message": "value2",
"status": "value3"
}

并用try JSONDecoder().decode([Object].self, from: data)解码通常会失败。

现在,我的问题是,有没有办法在这种(我会说不是很正常的架构 API)WITHOUT 中解码错误响应键创建一个名为 Objects 的 -复数 对象将具有可选属性 error , message , status ,例如 objects .
我的想法是扩展数组 where Element == Object并以某种方式尝试解码 error , message , status , 但我正在打 Conformance of 'Array<Element>' to protocol 'Decodable' was already stated in the type's module 'Swift' .也许那样做是不可能的,所以任何其他的,甚至是完全不同的建议都将非常受欢迎。

最佳答案

我的建议是将 JSON 的根对象解码为具有关联值的枚举

struct Item : Decodable {
let key1, key2, key3 : String
}

struct ResponseError : Decodable {
let error, message, status : String
}

enum Response : Decodable {
case success([Item]), failure(ResponseError)

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .success(try container.decode([Item].self))
} catch DecodingError.typeMismatch {
self = .failure(try container.decode(ResponseError.self))
}
}
}

并使用它

do {
let result = try JSONDecoder().decode(Response.self, from: data)
switch result {
case .success(let items): print(items)
case .failure(let error): print(error.message)
}
} catch {
print(error)
}

最好只捕获特定的 .typeMismatch 错误并立即将其他错误移交给调用者。

关于Swift Decodable,Endpoint返回完全不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792754/

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