A. K. M. Tariqul Islam
A. K. M. Tariqul Islam

Reputation: 2834

Retrofit parse selective JSON data

I am parsing JSON data from this URL. Calling like this:

call.enqueue(new Callback<List<Gift>>() {
    @Override
    public void onResponse(Call<List<Gift>> call, Response<List<Gift>> response) {
            List<Gift> places = response.body();
    }
}

But I don't want this. I want to first check if the flag is 0. If it is, then I want to get only the values of the list key. And want to use the following model:

class Gift extends RealmObject{
    String code, name;
    //getters & setters
}

How can I achieve this? Any help is highly appreciated.

Upvotes: 0

Views: 82

Answers (3)

Andy
Andy

Reputation: 469

You can create another POJO to store your Gift class, which store the outer value like flag and flag1, then you can access the flag to determine if you are going to go into list here is how it looks like:

class GiftResponse extends RealmObject{
    int flag;
    String flag1;
    Gift[] list;
    //getters & setters
}

and keep your Gift class as it is, then you can get the data like:

call.enqueue(new Callback<GiftResponse>() {
    @Override
    public void onResponse(Call<GiftResponse> call, Response<GiftResponse> response) {
            GiftResponse res = response.body();
            if(res.getFlag() == 0) {
                Gift[] arrGifts = res.getList();
            }
    }
}

ofcourse using this approach you change the call response type.

Upvotes: 1

Ayush Khare
Ayush Khare

Reputation: 1842

You can create a ResponseWrapper class as below:

public class ResponseWrapper<T> {

  private T data;
  @JsonProperty("flag")
  public int flag;
  @JsonProperty("flag1")
  public String flag1;

  public T getData() {
     return data;
  }
}

And modify your callback

call.enqueue(new Callback<ResponseWrapper<List<Gift>>>() {
   @Override
   public void onResponse(Call<ResponseWrapper<List<Gift>>> call, Response<ResponseWrapper<List<Gift>>> response) {
        int flag = response.body().flag;
        List<Gift> places = response.body().getData();
   }
}

Upvotes: 0

hareesh J
hareesh J

Reputation: 530

Try this way sample

class GiftList{
String flag;
String flag1;
List<Gift> gifts;

}

call.enqueue(new Callback<List<GiftList>>() {
    @Override
    public void onResponse(Call<List<GiftList>> call, Response<List<GiftList>> response) {
            List<GiftList> places = response.body();
      if(places.getFlag().equals("0"){
       List<Gift> gifts=places.getList();

    }
}

Upvotes: 1

Related Questions