How can I iterate through data class objects when there's JSON Object and not JSON Array?

Viewed 24

I am working on a project where one of the API is giving a list of items inside JSON Object and not in JSON Array. See the image below.

enter image description here

When I create a Kotlin data class using this JSON, it is created something similar to this:

data class Rates(
    var AED: Double = 0.0,
    var AFN: Double = 0.0,
    var ALL: Double = 0.0,
    var AMD: Double = 0.0,
    var ANG: Double = 0.0,
    var AOA: Double = 0.0,
    var ARS: Double = 0.0,
    ---------------------
    ---------------------

I wanted to show all the keys and values of the "rates" JSON object in RecyclerView. So I am not sure how can I convert this rates JSON object to a JSON Array in Kotlin response data class OR iterate through this data class Rates.

I wanted to convert this rates JSON Object to something like this data class of Kotlin so that it can be directly used in RecylerView without much headache:

data class CurrencyAndTypeList(
    var currencyAmount : Double = 0.0,
    var currencyType : String = "",
)

Any help will be appreciated. :)

1 Answers

Just tried and it works with Map<String, Float> type.

Here is my code:

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun main() {
    val asdf = Json.decodeFromString<Currency>(json)

    asdf.rates.entries.forEach {
        println("${it.key} value is ${it.value}")
    }
}

@Serializable
data class Currency(
    // here is the important part, make rates a map instead of individual properties
    val rates: Map<String, Float>,
)

val json = """
    {
        "rates": {
            "USD": 1.1,
            "EUR": 2.2
        }
        
    }
""".trimIndent()
Related