fastjson字段顺序问题

JAVA学习网 2018-06-22 15:53:03

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

阅读(1501) 评论(0)