2017-07-17 69 views
0

我正在解析來自this URL的JSON數據。打電話是這樣的:Retrofit解析選擇性JSON數據

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

但我不想這樣。我想先檢查flag是否爲0。如果是,那麼我只想得到list鍵的值。並且想要使用以下型號:

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

我該如何實現這一目標? 任何幫助是高度讚賞。

回答

1

嘗試這種方式樣品

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

    } 
} 
+0

如果我的項目包含很多API調用,而不是我需要創建許多像'GiftList'這樣我不想要的類。 –

+0

如果標誌字段對於所有api調用都是相同的,那麼不需要採用不同的類,那麼您可以在GiftList類中擁有多個實例它自己。否則,您可以使用ResponseWrapper類 –

0

您可以創建如下使用ResponseWrapper類:

public class ResponseWrapper<T> { 

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

    public T getData() { 
    return data; 
    } 
} 

和修改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(); 
    } 
} 
1

您可以創建另一個POJO來存儲您的Gift類,它存儲外部值,如flagflag1,那麼你就可以訪問flag,以確定你是否打算進入list 這裏是它的樣子:

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

,並保持你的Gift類,因爲它是,那麼你就可以獲取數據如:

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

of course使用這種方法您改變了呼叫響應類型。