【问题标题】:Handling JSON response dynamically for different fields of same type with retrofit in Android在 Android 中通过改造动态处理相同类型的不同字段的 JSON 响应
【发布时间】:2018-07-10 01:26:22
【问题描述】:

我在我的android 项目中使用retrofit2 和RxJava(不是RxJava2)。我有一个接受类型参数的端点。

@GET("api/v1/accounts/{account_type}")
Observable<ResponseAccountDetails> getAccountDetails(
                                         @Path("account_type") String accountType);

响应中的字段会根据帐户类型而变化,但数据保持不变。例如,

account_type = "free_account"时,POJO为

public class ResponseAccountDetails implements Serializable {
@SerializedName("free_account")
@Expose
private List<Account> account = null;

public List<Account> getAccount() {
    return account;
}}

account_type = "paid_account"时,POJO为

public class ResponseAccountDetails implements Serializable {
@SerializedName("paid_account")
@Expose
private List<Account> account = null;

public List<Account> getAccount() {
    return account;
}}

我知道的一种方法,也是更简单的一种方法是为每种类型设置不同的端点和不同的 POJO。

有没有更好更聪明的方法?只有一个端点可以根据提供的参数(account_type)动态更改响应(基本上)。 还有比我上面提到的更好的解决方案吗?

我希望我的问题很清楚。提前致谢。

【问题讨论】:

    标签: android rest retrofit rx-java retrofit2


    【解决方案1】:

    您不能为您的 POJO 使用备用名称吗?

    @SerializedName(value="free_account", alternate={"paid_account"})
    

    更多关于 GSON 文档here

    【讨论】:

      【解决方案2】:

      在@Diego Nolde 之外。你也可以这样用

      public class ResponseAccountDetails implements Serializable {
      @SerializedName("paid_account")
      @Expose
      private List<Account> account1 = null;
      
      @SerializedName("free_account")
      @Expose
      private List<Account> account2 = null;
      
      public List<Account> getAccount() {
          return account1 !=null?account1 :account2;
      }}
      

      【讨论】:

      • 是的,我想到了,但没有时看起来不太好。类型的增长。
      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 2020-09-15
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2017-06-21
      相关资源
      最近更新 更多