如何使可编码 class 解码没有 key/name 的 json 数组?
How to make codable class to decode json array which doesn't have a key/name?
我正在尝试解码 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"
}
}
我正在尝试解码 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"
}
}