如何使可编码类解码没有键/名称的json数组?

Zin*_*tet 1 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"
        }
]
Run Code Online (Sandbox Code Playgroud)

我的可编码类是..

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


struct UserWalletHistory: Codable{
    var Action: String?
    var Status: Int?
    var TransactionDate: String?
    var Description: String?
}
Run Code Online (Sandbox Code Playgroud)

但这并不成功。我认为这是因为变量名historyList,因为没有像historyListJSON 这样的键。那...那应该是什么?

vad*_*ian 6

删除 UserWalletHistoryList

struct UserWalletHistoryList: Codable {
   var historyList: [UserWalletHistory]
}
Run Code Online (Sandbox Code Playgroud)

并解码一个数组 UserWalletHistory

JSONDecoder().decode([UserWalletHistory].self, from: data)
Run Code Online (Sandbox Code Playgroud)

并且由于JSON提供了所有字典中的所有键,因此将struct成员声明为非可选成员,并添加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" 
    }
}
Run Code Online (Sandbox Code Playgroud)