-2

I'm trying to retrieve data from an api. The JSON response looks like this


{
    "result":"success",
    "documentation":"https://www.exchangerate-api.com/docs",
    "terms_of_use":"https://www.exchangerate-api.com/terms"
    "supported_codes":[
        ["AED","UAE Dirham"],
        ["AFN","Afghan Afghani"],
        ["ALL","Albanian Lek"],
        ["AMD","Armenian Dram"],
        ["ANG","Netherlands Antillian Guilder"],
        ["AOA","Angolan Kwanza"],
        ["ARS","Argentine Peso"],
        ["AUD","Australian Dollar"],
        ["AWG","Aruban Florin"],
        ["AZN","Azerbaijani Manat"],
        ["BAM","Bosnia and Herzegovina Convertible Mark"],
        ["BBD","Barbados Dollar"] etc. etc.
    ]
}

And this is the dataclass I have for it.

CurrencyResponse.kt


package com.example.currencyconverter.data

import com.squareup.moshi.Json

data class CurrencyResponse(
    @Json(name="supported_codes") var supported_codes: List<Codes>
) {
    data class Codes(
        @Json(name="0") var currency_code: String
    ) {

    }

}

Yet I'm still getting the error mentioned in the title. Any help is greatly appreciated

Ahmadddd4
  • 77
  • 7
  • I'm not very familiar with Gson, but it doesn't seem right that you deserialize array (e.g. `["AED","UAE Dirham"]`) to `Codes` object. You probably need something like this: `var supported_codes: List>` or maybe use a custom serializer. – broot Oct 25 '21 at 21:52

1 Answers1

0

If possible, I think the API response scheme need a little modification. I think the supported_codes should contains list of object instead, i.e.

    "supported_codes":[
        {
             "currency_code": "AED",
             "currency_name": "UAE Dirham"
        },
        {
             "currency_code": "AFN",
             "currency_name": "Afghan Afghani"
        },
        ... etc ...
    ]

Then, in your kotlin code, you need to modify the Codes data class to:

data class Codes(
   @Json(name="currency_code") val currencyCode: String,
   @Json(name="currency_name") val currencyName: String,
)
Putra Nugraha
  • 574
  • 1
  • 4
  • 12
  • But here's the thing, the array entries don't have a name so can I write "currency_code" and "currency_name" as names? – Ahmadddd4 Oct 26 '21 at 05:31
  • Unfortunately, it requires to change the API response schema as well. But, in my opinion, putting array of object inside `supported_codes` can help to ease the client side to identify the property passed, instead array of array – Putra Nugraha Oct 26 '21 at 06:57
  • I changed it to this ` data class CurrencyResponse( @Json(name ="supported_codes") val supportedCodes: List> ){ } ` The app no longer crashes but I'm getting a null response – Ahmadddd4 Oct 26 '21 at 07:02
  • Or, you can try to parse `supportedCodes` as answered in https://stackoverflow.com/a/17974337 – Putra Nugraha Oct 26 '21 at 07:36