Retrofit解析选择性JSON数据
问题描述:
我正在解析来自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
}
我该如何实现这一目标? 任何帮助是高度赞赏。
答
尝试这种方式样品
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();
}
}
答
您可以创建如下使用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();
}
}
答
您可以创建另一个POJO来存储您的Gift
类,它存储外部值,如flag
和flag1
,那么你就可以访问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使用这种方法您改变了呼叫响应类型。
如果我的项目包含很多API调用,而不是我需要创建许多像'GiftList'这样我不想要的类。 –
如果标志字段对于所有api调用都是相同的,那么不需要采用不同的类,那么您可以在GiftList类中拥有多个实例它自己。否则,您可以使用ResponseWrapper类 –