其他分享
首页 > 其他分享> > 解决fastjson解析数据后顺序改变的问题

解决fastjson解析数据后顺序改变的问题

作者:互联网

问题描述

使用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)

标签:fastjson,null,联通,300,16G,像素,2G,顺序,解析
来源: https://blog.csdn.net/weixin_44018458/article/details/121616936