1

I'm trying to decode following JSON to my codable object.

[
        {
            "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"
        }
]

My codable classes be like..

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


struct UserWalletHistory: Codable{
    var Action: String?
    var Status: Int?
    var TransactionDate: String?
    var Description: String?
}

but it is not successful. I think it's because of the variable name historyList since there is no such key as historyList in the JSON. Then..., what's it supposed to be?

1 Answer 1

6

Delete UserWalletHistoryList

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

and decode an array of UserWalletHistory

JSONDecoder().decode([UserWalletHistory].self, from: data)

and as the JSON provides all keys in all dictionaries declare the struct members as non-optional and add CodingKeys to map the uppercase keys to lowercase member names

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" 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I did not know that! I guess you could just use a typedef for the [ ] to keep it similar.
It works @vadian. And the CodingKeys stuff is really useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.