在 Swift 中使用 Codable 时如何保持灵活的结构

How to keep a flexible structure when using Codable in Swift

我有一个 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 class' detailresponse 属性 硬连接到 User 结构。但是,我的设置需要一点灵活性, 因为 detailresponse 当然会在调用不同端点时携带其他数据结构(例如,合作对象而不是用户对象)。

有没有一种优雅的方法可以使 Response class 中的 detailresponse 保持灵活而不是硬连接?或者通常更好的解决问题的方法?

你需要使用泛型

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)

这是泛型的用例:

class Response<T: Decodable>: Decodable {
   var statuscode: Int?
   var response_type: Int?
   // Other properties
   var detailresponse: T?
}

请注意,没有理由让属性可变。他们应该是 let。此外,struct 在这里可能是更好的选择。而且我认为应该有更少的选项,因为这应该是一个成功的响应。