Java json 对象中的 put 方法将值添加到 jsonobject 的第一个;
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4163343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
put method in the json object adds value to the first of the jsonobject;
提问by Roshan
Consider following piece of code:
考虑以下代码:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
如果我打印 jsonobject 它会像这样打印
{"three":"1","two":"2","one":"1"}
But i want like this.
但我想要这样。
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
请帮忙。提前致谢。
采纳答案by Saul
The documentation at http://www.json.org/javadoc/org/json/JSONObject.htmlsays:
http://www.json.org/javadoc/org/json/JSONObject.html 上的文档说:
A JSONObject is an unordered collection of name/value pairs.
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"]
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 Comparatormight help also.
解决您的问题的最简单方法是使用sortedKeys()方法,并通过按键迭代 JSONObject 键,以任何必要的顺序手动生成 JSON 字符串。实现自定义Comparator也可能有所帮助。