当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JSON 控制json的输出顺序(怎么存放怎么输出)

JSON 控制json的输出顺序(怎么存放怎么输出)

2020年07月24日  | 移动技术网IT编程  | 我要评论

直接在new的时候加一个LinkedHashMap就可以

  JSONObject jsonObject = new JSONObject(new LinkedHashMap());
  

注意:
可以同样进行深拷贝,但如果修改了深拷贝后的JSON属性值(JSON对象),会将此属性移动位置到第一个。其他String属性值不会修改位置.
如;

 JSONObject jsonObject = new JSONObject(new LinkedHashMap());
 jsonObject.put("name","张三");
 jsonObject.put("age","12");
 JSONObject other = new JSONObject(new LinkedHashMap());
 other.put("key","爱好");
 other.put("value","旅游");
 jsonObject.put("other",other);
 System.out.println("jsonObject===="+jsonObject.toJSONString());
 JSONObject copeJson=JSON.parseObject(jsonObject.toJSONString());
 JSONObject copeOther = JSON.parseObject(other.toJSONString());
  copeJson.put("age","20");
 copeOther.put("value","游泳");
 copeJson.put("other",copeOther);
 System.out.println("copeJson===="+copeJson.toJSONString());
 System.out.println("jsonObject===="+jsonObject.toJSONString()); 

输出(注意:我String值和Object值都重新赋值):

jsonObject===={"name":"张三","age":"12","other":{"key":"爱好","value":"旅游"}}
copeJson===={"other":{"value":"游泳","key":"爱好"},"name":"张三","age":"20"}
jsonObject===={"name":"张三","age":"12","other":{"key":"爱好","value":"旅游"}}

由以上可的出,如果是嵌套的JSON对象,重新赋值value为JSON对象的顺序会改变,而修改value值为String对象的则不会改变原有的顺序

本文地址:https://blog.csdn.net/qq_32786223/article/details/107533610

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

相关文章:

验证码:
移动技术网