问题描述
使用JSON.parseArray出现的情况
// 原始数据
[{"price":"121","num":"212","alertNum":"11","name":"1121 联通2G 5寸 16G 16G 300万像素 红 实施","spec":{"网络":"联通2G","手机屏幕尺寸":"5寸","机身内存":"16G","存储":"16G","像素":"300万像素","颜色":"红","测试":"实施"},"categoryId":3,"categoryName":"电子书","brandName":""}]
// 解析后的数据
Sku(id=null, sn=null, name=1121 联通2G 5寸 16G 16G 300万像素 红 实施, price=121, num=212, alertNum=11, image=null, images=null, weight=null, createTime=null, updateTime=null, spuId=null, categoryId=3, categoryName=电子书, brandName=, spec={"手机屏幕尺寸":"5寸","网络":"联通2G","颜色":"红","测试":"实施","机身内存":"16G","存储":"16G","像素":"300万像素"}, saleNum=null, commentNum=null, status=null)
主要变化如下"{"网络":"联通2G","手机屏幕尺寸":"5寸","机身内存":"16G","存储":"16G","像素":"300万像素","颜色":"红","测试":"实施"}
{"手机屏幕尺寸":"5寸","网络":"联通2G","颜色":"红","测试":"实施","机身内存":"16G","存储":"16G","像素":"300万像素"}
解决方法
可以使用JSON.parseObject来解决,它提供了Feature.OrderedField
参数
我们需要的是List类型,而JSON.parseArray
没有提供这个参数。那我们就先用JSON.parseObject把数据转换成List,再遍历List去转成对象
List list = JSON.parseObject(skus, List.class, Feature.OrderedField);
ArrayList<Sku> skuList = new ArrayList<>();
for (Object o : list) {
skuList.add(JSON.parseObject(String.valueOf(o),Sku.class,Feature.OrderedField));
}
skuList.forEach(System.out::println);
// Sku(id=null, sn=null, name=1121 联通2G 5寸 16G 16G 300万像素 红 实施, price=121, num=212, alertNum=11, image=null, images=null, weight=null, createTime=null, updateTime=null, spuId=null, categoryId=3, categoryName=电子书, brandName=, spec={"网络":"联通2G","手机屏幕尺寸":"5寸","机身内存":"16G","存储":"16G","像素":"300万像素","颜色":"红","测试":"实施"}, saleNum=null, commentNum=null, status=null)