【发布时间】:2019-11-23 16:40:51
【问题描述】:
我有一个这样的 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
我评论了我对代码所做的一切,请仔细阅读。非常感谢您的帮助..
【问题讨论】:
-
将其解析为 HashMap,然后使用 EntrySet 拉取键和值
标签: java android json kotlin retrofit