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

时间:2019-09-23 10:17:45

标签: 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这样的键。那...那应该是什么?

1 个答案:

答案 0 :(得分:6)

删除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" 
    }
}