如何在Android中使用具有一般响应的Retrofit

问题描述 投票:0回答:1

在我的应用程序中,我想使用 Retrofit 连接到服务器,并且我想调用 API。
我使用了这个 API:text
我想称之为终点:

https://api.coingecko.com/api/v3/simple/price?ids=01coin&vs_currencies=btc

回复如下所示:

{
  "01coin": {
    "btc": 1.3651e-8
  }
}

这个 json 的键(01coin 和 btc)是从端点查询创建的。
当改变硬币时,反应也改变了!我可以在 kotlin 中创建响应 json!

我在我的应用程序中调用了如下代码的 API

@GET("coins/list")
    suspend fun getCoinsList(): Response<ResponseCoinsList>

响应币列表:

class ResponseCoinsList : ArrayList<ResponseCoinsList.ResponseCoinsListItem>(){
    data class ResponseCoinsListItem(
        @SerializedName("id")
        val id: String?, // 01coin
        @SerializedName("name")
        val name: String, // 01coin
        @SerializedName("symbol")
        val symbol: String? // zoc
    )
}

如何在改造中使用带有 json 动态对象的响应类?

android kotlin retrofit
1个回答
0
投票

在改造中更新您的 get api 请求,如下

@GET("simple/price")
    suspend fun getCoinPrice(
        @Query("ids") coinId: String,
        @Query("vs_currencies") currency: String
    ): Response<Map<String, Map<String, Double>>> }

以及您调用 api 更新的位置,如下所示

GlobalScope.launch(Dispatchers.Main) {
    val coinId = "02coin" // Replace with your dynamic coin ID
    val currency = "py" // Replace with your dynamic currency

    val coinPriceResponse = apiRepository.getCoinPrice(coinId, currency)

    if (coinPriceResponse.isSuccessful) {
        val coinPriceData = coinPriceResponse.body()
        coinPriceData?.let {
            // Handle the response here
            val coinPrice = it.get(coinId)?.get(currency)
            Log.d("CoinPriceResponse", coinPrice.toString())
        } ?: run {
            // Handle the case where the coin price response is null
            Log.d("CoinPriceResponse", "Coin price data is null")
        }
    } else {
        // Handle the case where the coin price request is not successful
        Log.d("CoinPriceResponse", "Failed to fetch coin price")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.