GSON, KOTLIN – How can I access the nested value in a json link

  android, gson, json, kotlin, okhttp

{"status":"success","data":{"stats":{"total":11812,"offset":0,"limit":50,"order":"desc","base":"USD","totalMarkets":77572,"totalExchanges":372,"totalMarketCap":1710566042357.9397,"total24hVolume":76533943378.42046},"base":{"symbol":"USD","sign":"$"},"coins":[…..

This is the structure of the json but I cant seems to access to individual "coins" value

 fun fetchJson() {
    val url = "https://api.coinranking.com/v1/public/coins"
    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: okhttp3.Callback {
        override fun onFailure(call: okhttp3.Call, e: IOException) {
            println("Failed")
        }

        override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
            val body = response?.body?.string()
            println(body)

            val gson = GsonBuilder().create()
            val coins = gson.fromJson(body, coinrank::class.java)
            println("THESE ARE THE COINS : " +coins)
        }
    })
}
}

class coinrank(val status: String?, val data: Array?)

class dataR (val coins: List?)

class justCoin (
val id: Int?,
val name: String?,
val description: String?,
val slug: String?,
val symbol: String?,
val iconUrl: String?
)

There’s an error " Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 29 path $.data" on the
"val coins = gson.fromJson(body, coinrank::class.java)" sentence

I tried change the "val data: Array? to val data: JSONObject" but I still can’t find a way to access the values, can somebody help me?

Many thenter image description hereanks.

Source: Android Questions

One Reply to “GSON, KOTLIN – How can I access the nested value in a json link”

  • I’m getting the same error and it’s drive me crazy. Did u solve it? I think that it has something to be with the way that coinraking give us the “coins”: [{…}] that has this structure but can’t figure it out how to bypass this. Any idea?

LEAVE A COMMENT