fastjson字段顺序问题


最近在项目中用到阿里的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的顺序相同


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM