首页 > 解决方案 > 如何将类转换为可解码的 Json,如 Swift 中的@SerializedName?

问题描述

我需要创建一个两个类来解码 json 响应,例如 Kotlin 中的 @SerializedName,如下所示:

class PixHistoryResponse(
    @SerializedName("cadastro")
    var createdAt: String = "",
    @SerializedName("status")
    var status: String = "",
    @SerializedName("valor")
    var finalAmount: String = "",
    @SerializedName("timeline")
    var history: MutableList<PixTimelineResponse> = mutableListOf(),


@Keep
class PixTimelineResponse(
    @SerializedName("cadastro")
    var date: String = "",
    @SerializedName("status")
    var event: String = "",

标签: swiftxcode

解决方案


根据我的经验,我认为您应该struct用于建模数据,因为它是一种值类型。不应使用引用类型,如class.

struct PixHistoryResponse: Decodable {
    var createdAt: String = ""
    var finalAmount: String = "",
    var history: [PixTimelineResponse] = []

    enum CodingKeys: String, CodingKey {
        case createdAt = "cadastro"
        case finalAmount = "valor"
        case hisotry = "timeline"
    }
}

struct PixTimelineResponse: Decodable {
    var date: String = ""
    var event: String = ""
    
    enum CodingKeys: String, CodingKey {
        case data = "cadastro"
        case event = "status"
    }
}

推荐阅读