当前位置: 移动技术网 > IT编程>开发语言>Java > fastjson字段顺序问题

fastjson字段顺序问题

2018年06月21日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网