源码阅读计划之fastjson(一)

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值