我正在使用gson
所以我的要求是
@Override
public void onApiResonse(JSONObject response) {
ReportsOverviewDto dto = gjson.fromJson(response.toString(), ReportsOverviewDto.class);
ArrayList<ReportsOverviewDto.DataOverviewDto> data = dto.getData();
}
所以在我的班级ReportsOverviewDto
我有
public class ReportsOverviewDto {
private ArrayList<DataOverviewDto> data;
private String date_from, date_to;
...getters and setters and other classes
}
现在将数据作为
返回{"data":[{"total":588,"truck_category":26},
{"total":1646,"truck_category":27,},
{"total":1523,"truck_category":28}
],"date_to":"29\/03\/2018 03:03",
"date_from":"29\/03\/2017 03:03"}
每当服务器找不到记录时,它就会以表格形式返回数据
&#34;数据&#34;:{},&#34; date_to&#34;:&#34; 29/03/2018 03:03&#34;,&#34; date_from&#34;:&#34; 29/03/2018 03:03&#34;}
现在有了第二个响应,其中数据为{}
时出现错误
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 10 path $.data
我完全理解这是因为当它为空时,数据类型不再是一个arraylist而只是一个对象。
我如何确保即使它空了,应用程序也不会崩溃
答案 0 :(得分:0)
问题来自服务器端,因为它返回empty Object {}
而不是empty Array []
。但是,如果只想在客户端进行更改,这些将有所帮助:
Map<String,Object>
将JSON响应转换为fromJson()
。key=="data"
且值不是ArrayList
,则将该条目值转换为空ArrayList
。toJson()
从过滤后的地图(来自步骤2)返回JSON字符串。ReportsOverviewDto dto
将格式正确的JSON字符串(从第3步)转换为fromJson()
。答案 1 :(得分:0)
enter code here
公共类ReportsOverviewDto {
/**
* data : [{"total":588,"truck_category":26},{"total":1646,"truck_category":27},{"total":1523,"truck_category":28}]
* date_to : 29/03/2018 03:03
* date_from : 29/03/2017 03:03
*/
private String date_to;
private String date_from;
private List<DataBean> data;
public static List<ReportsOverviewDto> arrayReportsOverviewDtoFromData(String str) {
Type listType = new TypeToken<ArrayList<ReportsOverviewDto>>() {
}.getType();
return new Gson().fromJson(str, listType);
}
public String getDate_to() {
return date_to;
}
public void setDate_to(String date_to) {
this.date_to = date_to;
}
public String getDate_from() {
return date_from;
}
public void setDate_from(String date_from) {
this.date_from = date_from;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* total : 588
* truck_category : 26
*/
private int total;
private int truck_category;
public static List<DataBean> arrayDataBeanFromData(String str) {
Type listType = new TypeToken<ArrayList<DataBean>>() {
}.getType();
return new Gson().fromJson(str, listType);
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTruck_category() {
return truck_category;
}
public void setTruck_category(int truck_category) {
this.truck_category = truck_category;
}
}
}