【发布时间】:2020-04-18 11:04:51
【问题描述】:
我有一个 API 响应结构,代表一个用户对象,如下所示:
{
"statuscode": 200,
"response_type": 3,
"errormessage": null,
"detailresponse": {
"id": "2",
"shopifyautosync": null,
"platformfeepercentage": null,
"invited": null,
"requiresyoutubesocialmediaupdate": 1,
// Other properties ...
}
我正在使用 JSONDecoder().decode 解码为以下结构:
import Foundation
class Response: Decodable {
var statuscode: Int?
var response_type: Int?
// Other properties
var detailresponse: User?
}
import Foundation
class User: Codable {
var id: String?
var street: String?
var supporturl: String?
var verifiedaccount: Int?
var showfeatureupdatemodal: Int?
var admin: Int?
var email: String?
// Other properties
}
然后我是这样解码的:
let response = try JSONDecoder().decode(Response.self, from: jsonData)
我现在的主要问题是 Response 类的 detailresponse 属性硬连接到 User 结构。但是,我的设置需要一点灵活性, 因为 detailresponse 在调用不同的端点时当然会携带其他数据结构(例如,合作对象而不是用户对象)。
有没有一种优雅的方法来保持 Response 类中的 detailresponse 灵活而不是硬连接它?或者是一个更好的解决问题的方法?
【问题讨论】:
标签: swift codable jsondecoder