Android Gson对象解析

Android Gson对象解析,android,json,retrofit,retrofit2,gson,Android,Json,Retrofit,Retrofit2,Gson,有人能帮我在安卓系统中改型接收这个对象吗。我希望这些对象作为数组列表 {"UtilDataType":[{"name":"Pondicherry","id":22},{"name":"Vizianagaram","id":23},{"name":"Srikakulam","id":24}]} 我的API接口 public interface MyAPI { @GET("city") Call<ResponseBody> getCities(@Query("first") l

有人能帮我在安卓系统中改型接收这个对象吗。我希望这些对象作为数组列表

{"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 interface MyAPI {
   @GET("city")
   Call<UtilClass> getCities(@Query("first") long since, @Query("max") int perPage);
}
公共接口MyAPI{
@获取(“城市”)
调用getCities(@Query(“first”)很久以前,@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);
    }
  };
}
公共级城市{
私有int-id;
公共int getId(){
返回id;
}
公共无效集合id(内部id){
this.id=id;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
私有字符串名称;
public static DiffUtil.ItemCallback DIFF_CALLBACK=new DiffUtil.ItemCallback(){
@凌驾
公共布尔项相同(@NonNull City oldItem,@NonNull City newItem){
返回oldItem.id==newItem.id;
}
@凌驾
公共布尔值是相同的内容(@NonNull City oldItem,@NonNull City newItem){
返回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());
        }
    });
service.getCities(first,max).enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
Log.i(“blb07”,“+response.body().toString());
试一试{
UtilClass UtilClass=new Gson().fromJson(response.body().toString(),UtilClass.class);
//Log.i(“blb07”,“utilClass.getUtilDataType());
}捕获(例外e){
Log.i(“blb07”,“hello”+e.getMessage());
}
//JSONArray userArray=response.getJSONArray(“UtilDataType”);
//ArrayList temp=new Gson().fromJson(response.body().toString(),new TypeToken(){}.getType());
//Log.i(“blb07”和“+temp.size());
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Log.i(“blb07”,即“+t.getMessage());
}
});

我的目标是将这些城市对象放在android页面概念的arrylist中。现在我被困在这件事里了。有人来帮帮我。

response.string()
代替
response.body().toString()
。作为参考,您可以看到该类使用
response.string()
而不是
response.body().toString()
。作为参考,您可以看到此类手动解析忽略了使用;您需要对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
);
@GET(“城市”)
呼叫getCities(
@查询(“第一”)很久以前,
@每页查询(“最大”)整数
);
请看一个例子,它经常使用这个


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


当需要比较时,只需让class
UtilDataType
实现
comparable

手动解析就可以忽略使用;您需要对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
);
@GET(“城市”)
呼叫getCities(
@查询(“第一”)很久以前,
@每页查询(“最大”)整数
);
请看一个例子,它经常使用这个


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


当需要比较时,让class
UtilDataType
实现
comparable

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

我把实用课改成了

public class UtilClass {
   private ArrayList<City> UtilDataType;

   public ArrayList<City> getUtilDataType() {
     return UtilDataType;
   }

   public void setUtilDataType(ArrayList<City> utilDataType) {
     UtilDataType = utilDataType;
   }
}
公共类UtilClass{
私有ArrayList UtilDataType;
公共ArrayList getUtilDataType(){
返回UtilDataType;
}
public void setUtilDataType(ArrayList utilDataType){
UtilDataType=UtilDataType;
}
}
和我的界面

public interface MyAPI {
  @GET("city")
  Call<ResponseBody> getCities(@Query("first") long since, @Query("max") int perPage);
}
public interface MyAPI {
   @GET("city")
   Call<UtilClass> getCities(@Query("first") long since, @Query("max") int perPage);
}
公共接口MyAPI{
@获取(“城市”)
调用getCities(@Query(“first”)很久以前,@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);
        }
    });
service.getCities(first,max).enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.issusccessful()&&response.code()==200){
试一试{
字符串jsonString=new Gson().toJson(response.body());
UtilClass object=new Gson().fromJson(jsonString,UtilClass.class);
addAll(object.getUtilDataType());
onResult(城市);
}捕获(例外e){
Log.i(“blb07”,“hello”+e.getMessage());
}
}否则{
Log.i(“blb07”,response.message());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
字符串错误消息;
errorMessage=t.getMessage();
如果(t==null){
errorMessage=“未知错误”;
}
Log.i(“blb07”,错误消息);
}
});

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

我把实用课改成了

public class UtilClass {
   private ArrayList<City> UtilDataType;

   public ArrayList<City> getUtilDataType() {
     return UtilDataType;
   }

   public void setUtilDataType(ArrayList<City> utilDataType) {
     UtilDataType = utilDataType;
   }
}
公共类UtilClass{
私有ArrayList UtilDataType;
公共ArrayList getUtilDataType(){
返回UtilDataType;
}
public void setUtilDataType(ArrayList utilDataType){
UtilDataType=UtilDataType;
}
}
和我的界面

public interface MyAPI {
  @GET("city")
  Call<ResponseBody> getCities(@Query("first") long since, @Query("max") int perPage);
}
public interface MyAPI {
   @GET("city")
   Call<UtilClass> getCities(@Query("first") long since, @Query("max") int perPage);
}
公共接口MyAPI{
@获取(“城市”)
调用getCities(@Query(“first”)很久以前,@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);
        }
    });
service.getCities(first,max).enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.issusccessful()&&response.code()==200){
试一试{
字符串jsonString=new Gson().toJson(response.body());
UtilClass object=new Gson().fromJson(jsonString,UtilClass.class);
城市