gpt4 book ai didi

java - 如何在 Retrofit2 Android 中动态重命名 JSON 响应的键

转载 作者:行者123 更新时间:2023-12-02 13:34:49 27 4
gpt4 key购买 nike

我有这样的 JSON 响应:

    {
"AED_BDT": 23.100486
}

但是键会根据我的查询发生变化,例如我的查询是 USD_BDT ,然后它会给出这样的响应:
 {
"USD_BDT": 23.100486
}

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

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

这是我的模型课:
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

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

最佳答案

我猜 key 是从服务器定义的

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

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

关于java - 如何在 Retrofit2 Android 中动态重命名 JSON 响应的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59009872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com