Home > Blockchain >  How to get field names as an array from json in Kotlin
How to get field names as an array from json in Kotlin

Time:09-27

I am parsing the below sample json using retrofit in android:

{
    "success": true,
    "timestamp": 1664080564,
    "base": "EUR",
    "date": "2022-09-25",
    "rates": {
        "AED": 3.559105,
        "AFN": 86.151217,
        "ALL": 116.321643,
        "AMD": 404.265711
    }
}

As you can see there is no array in this json data, but I want the values of rates as a list or a map so that I can get "AED, AFN, ALL, AMD" as an array too. How can i achieve that using retrofit?

CodePudding user response:

You can define rates as a Map<String, Double> in your data class and Retrofit will automatically parse the rates in form of a Map.

data class MyModel(
    val success: Boolean,
    val timestamp: Long,
    val base: String,
    val date: String,
    val rates: Map<String, Double>
)

so that I can get "AED, AFN, ALL, AMD" as an array too.

For this you can simply use rates.keys to get all the keys.

  • Related