【问题标题】:Json array and retrofitJson 数组和改造
【发布时间】:2015-11-16 23:00:18
【问题描述】:

我有这种 json 响应:

 {
  error: false
  stats: {
          punti: 150
          punti2: 200
         }-
 }

我创建了一个 StatsReceiver 类:

public class StatsReceiver {
 Boolean error;
 Stats stat;

 public Boolean isError() {
     if (error == null)
         return true;
     else
         return error;
 }

 public int getPunti() {
     if (stat == null)
         return -1;
     else
         return stat.getPunti();
 }

 private class Stats {
     private int punti = 0;

     public int getPunti() {
         return punti;
     }

    public void setPunti(int punti) {
         this.punti = punti;
     }

     public int getPunti2() {
         return punti2;
     }

     public void setPunti2(int punti2) {
         this.punti2 = punti2;
     }

     private int punti2 = 0;

     public Stats(int punti, int punti2) {
         this.punti = punti;
         this.punti2 = punti2;
     }
 }
}

下一步:

 @GET("/v1/stats")
 void stats(@Header("Auth") String code,
              Callback<StatsReceiver> object);

现在当我这样做时:

 apiServiceUsers.stats(apiKey, new Callback<StatsReceiver>() {
        @Override
        public void success(StatsReceiver statsReceiver, Response response) {
            if (statsReceiver.isError()) {
                Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, statsReceiver.getPunti(), Toast.LENGTH_LONG).show();
            }
        }

错误是 false 符合预期,但 getPunti() 总是返回 -1,所以 stat 对象总是 null

怎么了?

P.S在Log控制台中,有:

 {"error":false,"stats":{"punti":150,"punti2":200}}

【问题讨论】:

    标签: java android json rest retrofit


    【解决方案1】:

    在您的 JSON 示例中,键是 stats;但在您的 Java 类中,成员变量称为 stat。要让 Gson 工作,这些必须要么完全相同,要么你必须使用 @SerializedName 告诉 Gson 哪个 JSON 键对应哪个变量:

    @SerializedName("stats")
    Stats statOrSomethingElseEntirely;
    

    【讨论】:

      猜你喜欢
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2017-09-02
      • 2018-03-19
      • 2017-08-02
      • 2015-05-24
      相关资源
      最近更新 更多