如何构建数据模型以进行正确的反序列化?

时间:2018-08-12 16:21:23

标签: android rest gson retrofit

我正在使用Retrofit 2.0调用货币换算API。 我在打电话:

https://free.currencyconverterapi.com/api/v6/convert?q=USD_PLN 

要收到此回复:

{
  "query": {
    "count": 1
  },
  "results": {
    "USD_PLN": {
      "id": "USD_PLN",
      "val": 3.763304,
      "to": "PLN",
      "fr": "USD"
    }
  }
}

现在,我正在尝试构建数据模型,以便Gson可以正确地反序列化此响应。我有ResponseWrapper.class

public class ResponseWrapper {

    private Query query;
    private ConversionPair results;

}

Query.class

public class Query {
    private int count;
}

ConversionPair.class

public class ConversionPair {
    private String id;
    private Currency from;
    private Currency to;
    private float value;
}

我应该如何处理响应正文中的USD_PLN对象?我希望能够用不同的电话对拨打不同的电话。我显然不会为每个可能的配对创建单独的类吗?处理该问题的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

最好的方法是让API小组更改字段并使其通用

 {  
   "query":{  
      "count":1
   },
   "results":{  
      "currency":{  // Currency should be fixed
         "id":"USD_PLN",
         "val":3.763304,
         "to":"PLN",
         "fr":"USD"
      }
   }
}

使用JsonToPojoConverter

public class Example {

    @SerializedName("query")

    private Query query;
    @SerializedName("results")

    private Results results;

    public Query getQuery() {
        return query;
    }

    public void setQuery(Query query) {
        this.query = query;
    }

    public Results getResults() {
        return results;
    }

    public void setResults(Results results) {
        this.results = results;
    }

}


public class Query {

    @SerializedName("count")

    private Integer count;

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

}


public class Results {

    @SerializedName("USD_PLN")

    private USDPLN uSDPLN;

    public USDPLN getUSDPLN() {
        return uSDPLN;
    }

    public void setUSDPLN(USDPLN uSDPLN) {
        this.uSDPLN = uSDPLN;
    }

}

public class USDPLN {

    @SerializedName("id")

    private String id;
    @SerializedName("val")

    private Double val;
    @SerializedName("to")

    private String to;
    @SerializedName("fr")

    private String fr;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Double getVal() {
        return val;
    }

    public void setVal(Double val) {
        this.val = val;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFr() {
        return fr;
    }

    public void setFr(String fr) {
        this.fr = fr;
    }

}

答案 1 :(得分:0)

使用JsonElement作为结果类型:JsonElement results;并将其手动转换为Map:

final Type type = new TypeToken<Map<String, ConversionPair>>(){}.getType();
final Map<String, ConversionPair> objects = new Gson().fromJson(results, type);

现在您可以遍历对象