fastJson源码阅读
fastJson实战
- json数据
{
"msg": "操作成功",
"code": 2001,
"data": {
"total": 1068774,
"update_time": "2019-10-05",
"day_visit_count": 12071,
"total_visit_count": 49321745,
"rows": [{
"food_name": "豇豆",
"production_name": "/",
"unqualified_num": 1,
"name_firset_letter": "J",
"food_mode": "散称",
"check_num": 6,
"qualified_num": 5,
"id": 762576
}, {
"food_name": "青柑",
"production_name": "/",
"unqualified_num": 0,
"name_firset_letter": "Q",
"food_mode": "/",
"check_num": 2,
"qualified_num": 2,
"id": 839148
}]
}
}
- javaBean
public class GoodsData {
private String FoodName;
private String ProductionName;
private int UnqualifiedNum;
private int NameFirsetLetter;
private String FoodMode;
private int CheckNum;
private int QalifiedNum;
private int id;
//getter/setter方法
...
}
- Result封装
public class Result<T> {
private int code;
private String msg;
private T data;
private int count;
//构造器/getter/setter
...
}
可以看出Result封装和Json不是一一对应的,所以没有采用直接Json直接转对象的方法,而是解析后自己填充封装。具体代码:
//fastjson 将 String 转换为 jsonObject
//JSONObject相当于map,JSONArray 相当于数组
JSONObject goodData = JSON.parseObject(httpOrgCreateTestRtn);
JSONObject data = (JSONObject) goodData.get("data");
String msg = (String) goodData.get("msg");
int code = (int) goodData.get("code");
int count = (int) data.get("total");
JSONArray rows = (JSONArray) data.get("rows");
List<GoodsData> list = new ArrayList<>();
for (int i = 0; i < rows.size(); i++) {
JSONObject obj = (JSONObject) rows.get(i);
GoodsData goodsData = new GoodsData();
goodsData.setId((Integer) obj.get("id"));
goodsData.setFoodName((String) obj.get("food_name"));
goodsData.setProductionName((String) obj.get("production_name"));
goodsData.setFoodMode((String) obj.get("food_mode"));
goodsData.setCheckNum((Integer) obj.get("check_num"));
goodsData.setQalifiedNum((Integer) obj.get("qualified_num"));
goodsData.setUnqualifiedNum((Integer) obj.get("unqualified_num"));
list.add(goodsData);
}
return Result.success(list,count);