Search code examples
androidkotlinretrofit

How to use Retrofit with general response in Android


In my application I want use Retrofit for connect to server and I want call API.
I used this APIs : text
And I want call this end point : https://api.coingecko.com/api/v3/simple/price?ids=01coin&vs_currencies=btc

In response show me such as below :

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

This keys (01coin & btc) of json create from end point query.
When change the coins, response also changed! and I can create response json in kotlin!

I called API such as below code in my application

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

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
    )
}

How can I use response class with dynamic object of json in retrofit?


Solution

  • update your get api request in retrofit as below

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

    and where you are calling your api update as below

    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")
        }
    }