BLB
BLB

Reputation: 893

Gson object parsing

Can someone help me receiving this object using retrofit in android. I want those objects as array list.

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

My API interface

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

My model class

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);
    }
  };
}

I tried many ways and still trying. Below is the method.

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());
        }
    });

My aim is to get those city objects in an arrylist for paging concept in android. Now I'm stuck in this thing. Someone help me please.

Upvotes: 0

Views: 70

Answers (3)

Chetan Sachdeva
Chetan Sachdeva

Reputation: 11

Use response.string() instead of response.body().toString(). For reference, you can see this class FlickrApiService

Upvotes: 0

BLB
BLB

Reputation: 893

Answering my own Question. Thank you Martin Zeitler, your examples are helpful.

I changed My UtilClass to

public class UtilClass {
   private ArrayList<City> UtilDataType;

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

   public void setUtilDataType(ArrayList<City> utilDataType) {
     UtilDataType = utilDataType;
   }
}

And my interface

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

And finally my main class

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);
        }
    });

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76569

manually parsing misses the point of using the GSON converter; you need to annotate the 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;
    }
}

then UtilDataType may be the expected data-type. for example:

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

see my GitHub client as an example, which uses this a lot ...


also, when response.body() does not have a value, try response.errorBody().string().

and when it is required to compare, just let class UtilDataType implement Compareable.

Upvotes: 2

Related Questions