json对象中的put方法将值添加到jsonobject中的第一个对象; [英] put method in the json object adds value to the first of the jsonobject;

查看:963
本文介绍了json对象中的put方法将值添加到jsonobject中的第一个对象;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

JSONObject json = new JSONObject(); 

json.put("one", 1); 

json.put("two", 2); 

json.put("three", 3);

如果我打印jsonobject,它会这样打印

If i print the jsonobject it prints like this

{"three":"1","two":"2","one":"1"}

但是我想要这样.

{"one":"1","two":"2","three":"3"}

请帮助.预先感谢.

推荐答案

http://www.json.org/javadoc/org/json/JSONObject.html 说:

JSONObject是名称/值对的无序集合.

换句话说,对象的属性是通过名称而不是位置来访问的,并且默认的序列化形式不能保证任何特定的顺序.

In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.

严格定位仅与数组一起提供:

Strict positioning comes only with arrays:

JSONArray json = new JSONArray();

json.put("1");
json.put("2");
json.put("3");

json.toString(); // results in ["1", "2", "3"]


解决问题的最简单方法是使用 sortedKeys ()方法,并通过一个密钥迭代JSONObject密钥,以必要的顺序手动生成JSON字符串.实施自定义比较器可能也有帮助


The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.

这篇关于json对象中的put方法将值添加到jsonobject中的第一个对象;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆