【发布时间】:2020-03-06 15:10:53
【问题描述】:
使用我正在使用的 API,我有一个案例,其中 1 个 API 端点可以根据调用是否成功返回完全不同的响应。
在成功的情况下,API Endpoint 在根中返回一个请求对象的数组,如下所示:
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
...
]
我通常用try JSONDecoder().decode([Object].self, from: data) 解码
如果出现错误,API Endpoint 会返回完全不同的内容,如下所示:
{
"error": "value1",
"message": "value2",
"status": "value3"
}
使用try JSONDecoder().decode([Object].self, from: data) 解码通常会失败。
现在,我的问题是,有没有办法在这种(我会说不是通常架构的 API)中解码错误响应键,没有创建一个名为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'。也许甚至不可能那样做,所以任何其他,甚至完全不同的建议都会非常受欢迎。
【问题讨论】:
标签: swift codable decodable swift-extensions jsondecoder