处理备用 API 响应类型(类型不匹配)
Handling Alternate API Response Types (typeMismatch)
我有一个 API 通常,它 returns 的响应是这样的:
{
"http_status": 200,
"error": false,
"message": "Success.",
"data": {
...
}
}
然而,当请求中出现错误时,响应如下所示:
{
"http_status": 409,
"error": true,
"message": "error message here",
"data": []
}
当我在此结构上使用 let decodedResponse = try JSONDecoder().decode(APIResponse.self, from: data)
时:
struct APIResponse: Codable {
var http_status: Int
var error: Bool
var message: String
var data: APIData?
}
有一个错误发生的情况,我得到响应:
Expected to decode Dictionary<String, Any> but found an array instead
我希望数据在解码对象中的位置 nil
。
有什么解决办法吗?
谢谢!
您可以自定义 JSON 响应如何被 overriding/implementing 和 init(from decoder: Decoder) throws {
解码
struct APIResponse: Codable {
enum CodingKeys: String, CodingKey {
// I'd rename this to conform to standard Swift conventions
// but for example...
case http_status = "http_status"
case error = "error"
case message = "message"
case data = "data"
}
var http_status: Int
var error: Bool
var message: String
var data: APIData?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
http_status = try container.decode(Int.self, forKey: .http_status)
error = try container.decode(Bool.self, forKey: .error)
message = try container.decode(String.self, forKey: .message)
guard !error else { return }
data = try container.decode(APIData.self, forKey: .data)
}
}
我有一个 API 通常,它 returns 的响应是这样的:
{
"http_status": 200,
"error": false,
"message": "Success.",
"data": {
...
}
}
然而,当请求中出现错误时,响应如下所示:
{
"http_status": 409,
"error": true,
"message": "error message here",
"data": []
}
当我在此结构上使用 let decodedResponse = try JSONDecoder().decode(APIResponse.self, from: data)
时:
struct APIResponse: Codable {
var http_status: Int
var error: Bool
var message: String
var data: APIData?
}
有一个错误发生的情况,我得到响应:
Expected to decode Dictionary<String, Any> but found an array instead
我希望数据在解码对象中的位置 nil
。
有什么解决办法吗?
谢谢!
您可以自定义 JSON 响应如何被 overriding/implementing 和 init(from decoder: Decoder) throws {
struct APIResponse: Codable {
enum CodingKeys: String, CodingKey {
// I'd rename this to conform to standard Swift conventions
// but for example...
case http_status = "http_status"
case error = "error"
case message = "message"
case data = "data"
}
var http_status: Int
var error: Bool
var message: String
var data: APIData?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
http_status = try container.decode(Int.self, forKey: .http_status)
error = try container.decode(Bool.self, forKey: .error)
message = try container.decode(String.self, forKey: .message)
guard !error else { return }
data = try container.decode(APIData.self, forKey: .data)
}
}