How to rename the key of a JSON Response dynamically in Retrofit2 Android

I have a JSON response like this:

    {
        "AED_BDT": 23.100486
    }

But the key changes according to my query like if my query is USD_BDT, then it will give response like this:

 {
        "USD_BDT": 23.100486
 }

So,that means I need to change the JSON key according to my query. But I couldn't find any solution on how to do this.

I tried by converting the response body into String and then replaced the Key according to my query, but this is not working..

This is my model class:

data class ResponseCurrencyConvert(
    val USD_BDT: Double
)

This is what I tried so far:

val params = HashMap<String,String>()
        params["compact"]="ultra"
        params["apiKey"]= API_KEY
        params["q"]="${currencyFrom}_${currencyTo}"//getting specific currencies and then setting them as query,i.e:USD_BDT
        message(TAG,"Query: ${params["q"]}")
        prefManager.query=params["q"]!!

        //calling the API
        apiServices.convertCurrency(params).enqueue(object : Callback<ResponseCurrencyConvert>{
            override fun onFailure(call: Call<ResponseCurrencyConvert>, t: Throwable) {
                message(TAG,"onFailure: ${t.localizedMessage}")
            }

            override fun onResponse(call: Call<ResponseCurrencyConvert>, response: Response<ResponseCurrencyConvert>) {
               message(TAG,"onResponse Code: ${response.code()}")
               message(TAG,"onResponse Body: ${Gson().toJson(response.body())}")

                val json = Gson().toJson(response.body())//converting the response as string
                val oldValue = "USD_BDT"//the key which was in my model class
                val newValue=params["q"]// the new key which is my query
                val output = json.replace(oldValue,newValue!!,false) // replacing the default query with my query
                val newResponse = Gson().fromJson(output,ResponseCurrencyConvert::class.java)//again converting the new replaced string to json

                    if (response.isSuccessful){

                    message(TAG,"Output: $output")
                    message(TAG,"onResponse Result: ${newResponse?.USD_BDT}")
                    message(TAG,"onResponse newResult: ${newResponse.USD_BDT}")
                    rate= newResponse?.USD_BDT//getting the value; this is returning 0 every time expect when my query is USD_BDT

I commented everything that I did on the code, please read that carefully. Your help is highly appreciated..

A way to do that is maintaining the 2 different keys, which is the most simple and effective.

Another way to accomplish this is changing the Response type to string. When you get the response you change the JSON string, changing the key name and then use GSON to manually convert from JSON to Object.

Maybe it can be done also with a Custom Json Converter, but I don't think is worth.

Consuming APIs with Retrofit, If you intend to use RxJava with Retrofit 2, you will also need to include the RxJava adapter: Assuming you have the JSON response already, go to jsonschema2pojo. Rename the class name Example to reflect your model name. @Query, specifies the query key name with the value of the annotated parameter. Imagine you’re in a situation where your backend can return a JSON response that’s dynamic in nature, a.k.a some parts of it don’t adhere to a specific pre-defined schema. Say you retrieve information about a webpage that you need to open in a WebView .

Keys are defined from the server only I guess

The best way you can do is like keep both keys and make it nullable

else you have an alternate name in JSON parsing

Gson Model Annotations — How to Change the Naming of Fields , Future Studio provides on-demand learning & wants you to become a better Android (Retrofit, Gson, Glide, Picasso) and Node.js/hapi� Let us create Android Spinner Example to Load JSON Using Retrofit in this article. In this tutorial, we will populate android spinner from MySQL database using retrofit and JSON data. To set the spinner value from JSON using retrofit, we will have to call one web service.

If the key changes for every other response, I would suggest using HashMap<String, String>. Instead of mapping directly to String value which changes dynamically using HashMap would solve your issue.

Let me know how it goes.

Gson Model Annotations — Multiple Deserialization Names with , by Norman Peitek on November 17 2016 , tagged in Gson, Android, Java , 5 min read Both JSON would result in the same Java object. If there are multiple� android documentation: Handling dynamic key for JSON response. android documentation: Handling dynamic key for JSON response. Retrofit2 with RxJava;

Retrofit an GSON: deserialize a specific object type based on the , Hi, I'm trying to deserialize a specific object type based on the value of a field. this is my json: { "orderId": 123121, "note": "notas raul", "percent": [ { "category": "Items" , some help from how you could do it in kotlin, use retrofit and GSON Upload multiple photos with queue, service and retrofit Android. Retrofit is a library for Android developed by Square to perform and handle REST API call in our Android application. Retrofit make it very easy to handle JSON response (or any other structured response) from REST API calls. In this tutorial, our example app will use Gson as converter to directly convert JSON response from our POST/GET calls to

Retrofit, String jsonString = new Gson(). String jsonString = gson. point, but not very reusable and also prone to errors in case we rename our attributes. once, and to dynamically annotate our fields without further modification. As we see, json keys for request and response are not following coding convention of Android, so we need to add SerializedName annotation for keys so that when we use Retrofit it generates proper

Exclude Fields from Serialization in Gson, sive analysis of application protocol behaviors for Android (request-response pairs) and identifies their message formats 9]*/android_ad.json?api-key=.* protocol fields and message formats, app-specific dynamic such as AsyncTask, volley, and retrofit. including Proguard, rename identifiers with semantically ob- . To interact with Retrofit to make a web-service request To parse a JSON object into Kotlin objects To rename Kotlin objects to match the keys in the JSON response

Comments
  • parse this as a HashMap and then pull keys and values using EntrySet
  • Thanks for your suggestion, I am trying this, but is it possible to change the key by using Interceptor? Because, generally interceptor is used for intercepting the response value using the keys.. I am very confused :(
  • @SoumikBhattacharjee Ok, maybe the Interceptor is not a good solution, I've added two more solutions, please take a look at the edited reply.
  • Thanks a lot for your time, I will try this and will let you know how it goes
  • Yes, finally your second solution worked, But as my response was a object so changing its type to String encountered an error, but going by your idea i change the response type to 'Any' and then converted the response as a String and got what i was looking for.. Thanks a lot man.
  • agree here, use 2 fields and you can use a property or function to get one value or the other checking which one is not null
  • Simple way { "Currency" : "USD_BDT" "USD_BDT": 23.100486, "AED_BDT": null } The server will only tell you which key you need to parse and based on that parse that key only
  • Thanks a lot for your suggestion, but these two are used for example only, In real I have a total of 152 currencies, and for every conversion the keys are different, so it would be very difficult to check all those.
  • Thanks for your suggestion, I'll definitely let you know