首页 > 解决方案 > 如何在 Retrofit2 Android 中动态重命名 JSON 响应的键

问题描述

我有这样的 JSON 响应:

    {
        "AED_BDT": 23.100486
    }

但是键会根据我的查询发生变化,例如如果我的查询是USD_BDT,那么它将给出如下响应:

 {
        "USD_BDT": 23.100486
 }

所以,这意味着我需要根据我的查询更改JSON键。但是我找不到有关如何执行此操作的任何解决方案。

我尝试将响应正文转换为字符串,然后根据我的查询替换密钥,但这不起作用..

这是我的模型课:

data class ResponseCurrencyConvert(
    val USD_BDT: Double
)

这是我到目前为止所尝试的:

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

我评论了我对代码所做的一切,请仔细阅读。非常感谢您的帮助..

标签: javaandroidjsonkotlinretrofit

解决方案


我猜密钥是从服务器定义的

您可以做的最好的方法是保留两个键并使其可以为空

否则你在 JSON 解析中有一个备用名称


推荐阅读