swift - 如何制作可编码类来解码没有键/名称的 json 数组?

标签 swift codable

我正在尝试将 JSON 解码为我的可编码对象。

[
        {
            "Action": "CREDIT",
            "Status": 1,
            "TransactionDate": "2019-09-20T04:23:19.530137Z",
            "Description": "test"
        },
        {
            "Action": "CREDIT",
            "Status": 1,
            "TransactionDate": "2019-09-20T04:23:19.530137Z",
            "Description": "test"
        },
        {
            "Action": "CREDIT",
            "Status": 1,
            "TransactionDate": "2019-09-20T04:23:19.530137Z",
            "Description": "test"
        }
]

我的可编码类就像..

struct UserWalletHistoryList: Codable {
    var historyList: [UserWalletHistory]
}


struct UserWalletHistory: Codable{
    var Action: String?
    var Status: Int?
    var TransactionDate: String?
    var Description: String?
}

但是没有成功。我认为这是因为变量名 historyList 因为在 JSON 中没有像 historyList 这样的键。那么……,它应该是什么?

最佳答案

删除UserWalletHistoryList

<罢工>

<罢工>
struct UserWalletHistoryList: Codable {
   var historyList: [UserWalletHistory]
}

<罢工>

并解码 UserWalletHistory 的数组

JSONDecoder().decode([UserWalletHistory].self, from: data)

并且由于 JSON 提供所有字典中的所有键,将结构成员声明为非可选的,并添加 CodingKeys 以将大写键映射到小写成员名称

struct UserWalletHistory : Codable {
    let action: String
    let status: Int
    let transactionDate: String
    let description: String

    private enum CodingKeys : String, CodingKey { 
        case action = "Action"
        case status = "Status"
        case transactionDate = "TransactionDate"
        case description = "Description" 
    }
}

关于swift - 如何制作可编码类来解码没有键/名称的 json 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060211/

相关文章:

ios - CMSensorRecorder 未获得授权,但系统从未提示我授予授权?

ios - 读取 BLE 外设特性并检查其值?

ios - 类型 'PlayerConfiguration' 没有成员 'fromJson' Bitmovin iOS 集成错误

swift - Codable/Decodable 应该用字符串解码数组

swift - 使用可选类型时的 RealmSwift 和 Codable

ios - 使用 `default values` 快速创建非可选 Codable 的最佳方法

swift - 初始化期间可编码的默认值

macos - Swift:调整嵌入式自定义 NSView 的大小

swift - 调用与我的数据库交互的方法的最佳位置在哪里?

json - 使用 Codable 协议(protocol)从 JSON API 解码包含的部分