【问题标题】:Gson object parsingGson 对象解析
【发布时间】:2019-01-22 16:06:26
【问题描述】:

有人可以帮助我在 android 中使用改造来接收这个对象吗?我希望这些对象作为数组列表。

{"UtilDataType":[{"name":"Pondicherry","id":22},{"name":"Vizianagaram","id":23},{"name":"Srikakulam","id":24}]}

我的 API 接口

public interface MyAPI {
  @GET("city")
  Call<ResponseBody> getCities(@Query("first") long since, @Query("max") int perPage);
}

我的模型课

public class City {
   private int id;

   public int getId() {
     return id;
   }

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

  public String getName() {
     return name;
  }

  public void setName(String name) {
     this.name = name;
  }

  private String name;
  public static DiffUtil.ItemCallback<City> DIFF_CALLBACK = new DiffUtil.ItemCallback<City>() {
    @Override
    public boolean areItemsTheSame(@NonNull City oldItem, @NonNull City newItem) {
        return oldItem.id == newItem.id;
    }

    @Override
    public boolean areContentsTheSame(@NonNull City oldItem, @NonNull City newItem) {
        return oldItem.equals(newItem);
    }
  };
}

我尝试了很多方法,但仍在尝试。下面是方法。

service.getCities(first,max).enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.i("blb07",""+response.body().toString());

            try {
                UtilClass utilClass=new Gson().fromJson(response.body().toString(),UtilClass.class);
                //Log.i("blb07",""+utilClass.getUtilDataType());
            }catch (Exception e){
                Log.i("blb07","hello "+e.getMessage());
            }
            //JSONArray userArray = response.getJSONArray("UtilDataType");
            //ArrayList<City> temp=new Gson().fromJson(response.body().toString(), new TypeToken<List<City>>() {}.getType());
            //Log.i("blb07",""+temp.size());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.i("blb07",""+t.getMessage());
        }
    });

我的目标是将这些城市对象放在一个 arrylist 中,用于 android 中的分页概念。现在我被困在这件事上。请有人帮帮我。

【问题讨论】:

    标签: android json retrofit retrofit2 gson


    【解决方案1】:

    手动解析错过了使用GSON converter的要点;您需要注释 POJO:

    import com.google.gson.annotations.SerializedName;
    
    public class UtilDataType {
    
        @SerializedName("id")
        private Long id;
    
        @SerializedName("name")
        private String name;
    
        @NonNull
        public Long getId() {
            return this.id;
        }
    
        @NonNull
        public String getName() {
            return this.name;
        }   
    
        public void setId(Long value) {
            this.id = value;
        }
    
        public void setName(String value) {
            this.name = value;
        }
    }
    

    那么UtilDataType 可能是预期的数据类型。例如:

    @GET("city")
    Call<UtilDataType> getCities(
        @Query("first") long since,
        @Query("max") int perPage
    );
    

    my GitHub client 为例,它使用了很多...


    另外,当response.body() 没有值时,试试response.errorBody().string()

    当需要比较时,让UtilDataType类实现Compareable即可。

    【讨论】:

      【解决方案2】:

      回答我自己的问题。谢谢 Martin Zeitler,你的例子很有帮助。

      我将我的 UtilClass 更改为

      public class UtilClass {
         private ArrayList<City> UtilDataType;
      
         public ArrayList<City> getUtilDataType() {
           return UtilDataType;
         }
      
         public void setUtilDataType(ArrayList<City> utilDataType) {
           UtilDataType = utilDataType;
         }
      }
      

      还有我的界面

      public interface MyAPI {
         @GET("city")
         Call<UtilClass> getCities(@Query("first") long since, @Query("max") int perPage);
      }
      

      最后是我的主要课程

      service.getCities(first,max).enqueue(new Callback<UtilClass>() {
              @Override
              public void onResponse(Call<UtilClass> call, Response<UtilClass> response) {
                  if (response.isSuccessful() && response.code() == 200) {
      
                      try {
                          String jsonString=new Gson().toJson(response.body());
                          UtilClass object=new Gson().fromJson(jsonString,UtilClass.class);
      
                          cities.addAll(object.getUtilDataType());
                          callback.onResult(cities);
      
                      }catch (Exception e){
                          Log.i("blb07","hello "+e.getMessage());
                      }
                  } else {
                      Log.i("blb07", response.message());
                  }
              }
      
              @Override
              public void onFailure(Call<UtilClass> call, Throwable t) {
                  String errorMessage;
                  errorMessage = t.getMessage();
                  if (t == null) {
                      errorMessage = "unknown error";
                  }
                  Log.i("blb07",errorMessage);
              }
          });
      

      【讨论】:

        【解决方案3】:

        使用response.string() 而不是response.body().toString()。供参考,可以看这个类FlickrApiService

        【讨论】:

        • 在java string()方法不可用
        • 我写错了表达式(现已编辑)。使用resonse.string()
        猜你喜欢
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 2013-10-14
        • 1970-01-01
        相关资源
        最近更新 更多