如何使用带有Kotlin的Gson库访问JSON有效负载中的嵌套值

cgfeq70w  于 2022-11-06  发布在  Kotlin
关注(0)|答案(1)|浏览(193)

我需要解析下面的JSON负载:

{
  "status": "success",
  "data": {
    "stats": {
      "total": 11812,
      "offset": 0,
      "limit": 50,
      "order": "desc",
      "base": "USD",
      "totalMarkets": 77573,
      "totalExchanges": 372,
      "totalMarketCap": 1692792022714.2244,
      "total24hVolume": 78345365115.11235
    },
    "base": {
      "symbol": "USD",
      "sign": "$"
    },
    "coins": [
      {
        "id": 1,
        "uuid": "Qwsogvtv82FCd",
        "slug": "bitcoin-btc",
        "symbol": "BTC",
        "name": "Bitcoin",
   ...
}

我对“硬币”的价值有一个问题:

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<dataR>?)

class dataR (val coins: List<justCoin>?)

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

发生错误:
导致错误的原因:java.lang.路径$.data的第1行第29列应为开始_ARRAY,但实际上是BEGIN_OBJECT
在线上:val coins = gson.fromJson(body, coinrank::class.java)
我尝试将val data: Array<dataR>?更改为val data: JSONObject“,但我仍然无法找到访问这些值的方法,有人能帮助我吗?

pepwfjgg

pepwfjgg1#

您的数据模型不适合JSON有效负载。请尝试以下操作:

data class CoinsResponse(
    val status: String,
    val data: CoinsData
)

data class CoinsData(
    val coins: List<Coin>
)

data class Coin(
    val id: Int,
    val symbol: String,
    val name: String
)

示例用法:

val gson = GsonBuilder().create()
val response = gson.fromJson(body, CoinsResponse::class.java)
response.data.coins.forEach(System.out::println)

以上代码应打印:

Coin(id=1, symbol=BTC, name=Bitcoin)
Coin(id=2, symbol=ETH, name=Ethereum)
Coin(id=8, symbol=USDT, name=Tether USD)
Coin(id=14, symbol=BNB, name=Binance Coin)
Coin(id=9, symbol=ADA, name=Cardano)
Coin(id=3, symbol=XRP, name=XRP)
...

相关问题