【问题标题】:How to handle dynamic changing JSON object in android如何在android中处理动态变化的JSON对象
【发布时间】:2020-12-04 06:34:38
【问题描述】:

我有一个来自 API 的 JSON,它返回类似这样的内容 -

{
 "amount": "10.0000",
 "base_currency_code": "EUR",
 "base_currency_name": "Euro",
   "rates": {
      "GBP": {
       "currency_name": "Pound Sterling",
       "rate": "0.9060",
       "rate_for_amount": "9.0601"
     }
   },
   "status": "success",
   "updated_date": "2020-12-03"
}

从上面的数据来看,json Object GBP的值会根据选择的货币代码而变化。

例如,如果用户选择了美元,则将更改为 美元

所以,我复制了代码并使用插件将 JSON 转换为 kotlin 数据类 -

ApiResponse.class

data class ApiResponse(
val amount: String,
val base_currency_code: String,
val base_currency_name: String,
val rates: Rates,
val status: String,
val updated_date: String
)

data class Rates(
val GBP: GBP
)

data class GBP(
val currency_name: String,
val rate: String,
val rate_for_amount: String
)

如您所见,它为发生变化的 JSON 对象 GBP 生成了一个静态类。

如何生成我的 POJO 类,指定 JSON 对象“GBP”根据选择的内容而变化。

我正在使用 Retrofit 和 GSON 转换器。

【问题讨论】:

  • GBP 保留为Map<String, String>

标签: android json kotlin retrofit2


【解决方案1】:

如果您使用 GSON,最好将 JsonDeserializer<T> 用于自定义解析模型。


private class GBPDeserializer implements JsonDeserializer<GBP> {

  @Override
  public GBP deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

       //TODO: You should JsonElement convert to JSONObject and by keys()
               method run a dynamically loop and resolve fileds.
 
  }  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2017-11-24
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多