java - 如何在 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
我评论了我对代码所做的一切,请仔细阅读。非常感谢您的帮助..
解决方案
我猜密钥是从服务器定义的
您可以做的最好的方法是保留两个键并使其可以为空
否则你在 JSON 解析中有一个备用名称
推荐阅读
- r - 有没有办法让函数返回数据框?
- common-lisp - 为什么是(等于(复制-
) ) 无? - path-finding - 在 Godot 中, get_simple_path() 返回的路径似乎被某些东西抵消了
- python - ValueError:训练 CNN 模型时无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
- f# - F#如何向上转换泛型
- unity3d - 如何获取 2D Sprite 正面的光照信息?
- javascript - 在将一个对象值分配给另一个变量之后。它改变了我的旧对象
- python - 如何在 spotify 中创建可点击的 Windows 应用程序链接?
- mongodb - typeorm:migration create on New Project Does Not Recognize Entities - “未发现数据库架构更改 - 无法生成迁移。”
- java - 如何使用 PAX a 920 打印收据?