我正在尝试将 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/