我正在尝试将以下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,因为没有像historyList
JSON 这样的键。那...那应该是什么?
删除 UserWalletHistoryList
struct UserWalletHistoryList: Codable { var historyList: [UserWalletHistory] }
并解码一个数组 UserWalletHistory
JSONDecoder().decode([UserWalletHistory].self, from: data)
并且由于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" } }