最近在项目中用到阿里的fastjson,发现一个问题:
JSONObject fastJson = new JSONObject(); fastJson.put("1", "1"); fastJson.put("2", "1"); fastJson.put("3", "1"); fastJson.put("11", "1"); fastJson.put("22", "1"); fastJson.put("33", "1"); fastJson.put("111", "1"); fastJson.put("222", "1"); fastJson.put("333", "1"); System.out.println(fastJson.toJSONString());
上述代码的输出为:
元素顺序和put的顺序并不相同
查看了一下fastjson的源码
发现其默认的构造函数中使用的是HashMap,想要元素顺序和put的顺序相同,需要新建对象时指定为有序,这样使用的就是LinkedHashMap,是有序的
测试一下:
JSONObject fastJson = new JSONObject(true); fastJson.put("1", "1"); fastJson.put("2", "1"); fastJson.put("3", "1"); fastJson.put("11", "1"); fastJson.put("22", "1"); fastJson.put("33", "1"); fastJson.put("111", "1"); fastJson.put("222", "1"); fastJson.put("333", "1"); System.out.println(fastJson.toJSONString());
输出结果为:
元素顺序和put的顺序相同
如对本文有疑问, 点击进行留言回复!!
SpringBoot引用阿里easyexcel,Excel导出返回浏览器下载
HashMap、Hashtable、ConcurrentHashMap三者间的异同
解决RecycleView 中Item包含Edittext时,滑动view复用导致数据错乱的问题
多线程、同步工作原理、死锁案例、Lock接口、线程的生命周期的讲解及实现
网友评论