如何使用带有 Kotlin 的 Gson 库访问 JSON 有效负载中的嵌套值
Posted
技术标签:
【中文标题】如何使用带有 Kotlin 的 Gson 库访问 JSON 有效负载中的嵌套值【英文标题】:How can I access the nested value in a JSON payload using Gson library with Kotlin 【发布时间】:2021-10-07 04:56:24 【问题描述】:下面需要解析JSON
payload:
"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.IllegalStateException:预期 BEGIN_ARRAY 但 在第 1 行第 29 列路径 $.data 处为 BEGIN_OBJECT
在线:val coins = gson.fromJson(body, coinrank::class.java)
我尝试将 val data: Array<dataR>?
更改为 val data: JSONObject
" 但我仍然找不到访问这些值的方法,有人可以帮助我吗?
【问题讨论】:
【参考方案1】:您的数据模型不适合 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)
...
【讨论】:
以上是关于如何使用带有 Kotlin 的 Gson 库访问 JSON 有效负载中的嵌套值的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin编程开发Android运用程序(Volley+Gson依赖库)
Android Kotlin API 请求 | gson进程后访问列表
Kotlin基础从入门到进阶系列讲解(入门篇)Android之GSON的使用