swift - 如何将类转换为可解码的 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 = "",
解决方案
根据我的经验,我认为您应该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"
}
}
推荐阅读
- amazon-web-services - 谁停止和启动 ECS 任务?并通知 ECS 服务
- gradle - 如何将文本文件添加到 Gradle 中的类路径?
- python - 错误在哪里以及如何避免错误字符错误
- javascript - 调用 URL 时对我的 JavaScript 代码感到困惑,不确定是否需要 Ajax 调用
- c - 通过SDL覆盖linux桌面条目中的图标
- android - 刷新时在 textview 上显示文本的字符串数组
- python - python中的heapq模块可以使用哪些类型的堆元素?
- java - 为什么设置新键盘后我的 Android 自定义 KeyboardView 会溢出?
- php - 如何在 AJAX 中显示 MYSQL 错误?
- vba - 如何获取 Word 邮件合并文档中包含的记录列表?