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

i7uq4tfw  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(140)

在我的应用程序中,我想使用Retrofit连接到服务器,我想调用API。
我使用了这个API:text
我想把这个端点命名为:https://api.coingecko.com/api/v3/simple/price?ids=01coin&vs_currencies=btc
在响应显示我如下图:

  1. {
  2. "01coin": {
  3. "btc": 1.3651e-8
  4. }
  5. }

字符串
这个键(01 coin & btc)的json创建从终点查询.
当改变硬币时,响应也改变了!我可以在Kotlin中创建响应json!
我调用了API,如下面的代码在我的应用程序

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

ResponseCoinsList:

  1. class ResponseCoinsList : ArrayList<ResponseCoinsList.ResponseCoinsListItem>(){
  2. data class ResponseCoinsListItem(
  3. @SerializedName("id")
  4. val id: String?, // 01coin
  5. @SerializedName("name")
  6. val name: String, // 01coin
  7. @SerializedName("symbol")
  8. val symbol: String? // zoc
  9. )
  10. }


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

qxgroojn

qxgroojn1#

如下所示在改造中更新get API请求

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

字符串
以及在何处调用API更新,如下所示

  1. GlobalScope.launch(Dispatchers.Main) {
  2. val coinId = "02coin" // Replace with your dynamic coin ID
  3. val currency = "py" // Replace with your dynamic currency
  4. val coinPriceResponse = apiRepository.getCoinPrice(coinId, currency)
  5. if (coinPriceResponse.isSuccessful) {
  6. val coinPriceData = coinPriceResponse.body()
  7. coinPriceData?.let {
  8. // Handle the response here
  9. val coinPrice = it.get(coinId)?.get(currency)
  10. Log.d("CoinPriceResponse", coinPrice.toString())
  11. } ?: run {
  12. // Handle the case where the coin price response is null
  13. Log.d("CoinPriceResponse", "Coin price data is null")
  14. }
  15. } else {
  16. // Handle the case where the coin price request is not successful
  17. Log.d("CoinPriceResponse", "Failed to fetch coin price")
  18. }
  19. }

展开查看全部

相关问题