在Swift中使用Codable时如何保持灵活的结构 [英] How to keep a flexible structure when using Codable in Swift
问题描述
我有一个表示用户对象的API响应结构,如下所示:
I've got a API response structure, representing a user object, that looks like this:
{
"statuscode": 200,
"response_type": 3,
"errormessage": null,
"detailresponse": {
"id": "2",
"shopifyautosync": null,
"platformfeepercentage": null,
"invited": null,
"requiresyoutubesocialmediaupdate": 1,
// Other properties ...
}
我正在使用JSONDecoder().decode解码为以下结构:
I'm using JSONDecoder().decode to decode to following structures:
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
}
这就是我随后进行解码的方式:
Here's how I then decode:
let response = try JSONDecoder().decode(Response.self, from: jsonData)
我现在的主要问题是Response类的detailresponse属性被硬连接到User结构.但是,我在设置时需要一些灵活性, 因为在调用不同的端点(例如,合作对象而不是用户对象)时,detailresponse当然会携带其他数据结构.
My main problem now is that the Response class' detailresponse property is hard-wired to a User struct. However, I need a little flexibility in my setup, as the detailresponse will, of course, carry other data structures when calling different endpoints (e.g. a cooperation object instead of a user object).
是否有一种优雅的方法来使detailResponse保持在Response类内部灵活而不是繁琐地布线?还是用一般更好的方法来解决问题?
Is there an elegant way to keep the detailresponse inside the Response class flexible instead of hard-wiring it? Or a generally better approach to the problem instead?
推荐答案
您需要使用泛型
class Response<T:Decodable>: Decodable {
var statuscode: Int?
var response_type: Int?
// Other properties
var detailresponse: T?
}
然后
let response = try JSONDecoder().decode(Response<User>.self, from: jsonData)
这篇关于在Swift中使用Codable时如何保持灵活的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!