Java JSON 顺序混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3948206/
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
JSON order mixed up
提问by JSON guy
I've a problem trying to make my page printing out the JSONObject
in the order i want. In my code, I entered this:
我在尝试JSONObject
按照我想要的顺序打印我的页面时遇到问题。在我的代码中,我输入了这个:
JSONObject myObject = new JSONObject();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
However, when I see the display on my page, it gives:
但是,当我看到页面上的显示时,它给出:
JSON formatted string: [{"success":"NO", "userid":"User 1", "bid":24.23}]
JSON 格式的字符串: [{"success":"NO", "userid":"User 1", "bid":24.23}]
I need it in the order of userid, amount, then success. Already tried re-ordering in the code, but to no avail. I've also tried .append
....need some help here thanks!!
我需要它的顺序是用户 ID,金额,然后是成功。已经尝试在代码中重新排序,但无济于事。我也试过.append
......在这里需要一些帮助谢谢!
回答by Mark Snidovich
JavaScript objects, and JSON, have no way to set the order for the keys. You might get it right in Java (I don't know how Java objects work, really) but if it's going to a web client or another consumer of the JSON, there is no guarantee as to the order of keys.
JavaScript 对象和 JSON 无法设置键的顺序。您可能会在 Java 中得到它(我真的不知道 Java 对象是如何工作的)但是如果它要发送到 Web 客户端或 JSON 的另一个使用者,则无法保证键的顺序。
回答by Adrian Smith
You cannot and should not rely on the ordering of elements within a JSON object.
您不能也不应该依赖 JSON 对象中元素的顺序。
From the JSON specification at http://www.json.org/
来自http://www.json.org/ 上的 JSON 规范
An object is an unordered set of name/value pairs
对象是一组无序的名称/值对
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
因此,JSON 库可以按照他们认为合适的方式自由地重新排列元素的顺序。这不是一个错误。
回答by lemiorhan
I agree with the other answers. You cannot rely on the ordering of JSON elements.
我同意其他答案。您不能依赖 JSON 元素的顺序。
However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMapobject with elements and convert it to JSONObject.
但是,如果我们需要一个有序的 JSON,一种解决方案可能是准备一个包含元素的LinkedHashMap对象并将其转换为 JSONObject。
@Test
def void testOrdered() {
Map obj = new LinkedHashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Ordered Json : %s", json.toString())
String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
assertEquals(expectedJsonString, json.toString())
JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}
Normally the order is not preserved as below.
通常,顺序不会如下保留。
@Test
def void testUnordered() {
Map obj = new HashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Unordered Json : %s", json.toString(3, 3))
String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
// string representation of json objects are different
assertFalse(unexpectedJsonString.equals(json.toString()))
// json objects are equal
JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}
You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html
你也可以查看我的帖子:http: //www.flyingtomoon.com/2011/04/preserving-order-in-json.html
回答by Kartikya
As all are telling you, JSON does not maintain "sequence" but array does, maybe this could convince you: Ordered JSONObject
正如所有人都告诉你的那样,JSON 不维护“序列”但数组可以,也许这可以说服你: Ordered JSONObject
回答by sang
from lemiorhan example i can solve with just change some line of lemiorhan's code use:
从 lemiorhan 示例中,我只需更改一些 lemiorhan 的代码使用行即可解决:
JSONObject json = new JSONObject(obj);
instead of this:
而不是这个:
JSONObject json = (JSONObject) obj
so in my test code is :
所以在我的测试代码中是:
Map item_sub2 = new LinkedHashMap();
item_sub2.put("name", "flare");
item_sub2.put("val1", "val1");
item_sub2.put("val2", "val2");
item_sub2.put("size",102);
JSONArray itemarray2 = new JSONArray();
itemarray2.add(item_sub2);
itemarray2.add(item_sub2);//just for test
itemarray2.add(item_sub2);//just for test
Map item_sub1 = new LinkedHashMap();
item_sub1.put("name", "flare");
item_sub1.put("val1", "val1");
item_sub1.put("val2", "val2");
item_sub1.put("children",itemarray2);
JSONArray itemarray = new JSONArray();
itemarray.add(item_sub1);
itemarray.add(item_sub1);//just for test
itemarray.add(item_sub1);//just for test
Map item_root = new LinkedHashMap();
item_root.put("name", "flare");
item_root.put("children",itemarray);
JSONObject json = new JSONObject(item_root);
System.out.println(json.toJSONString());
回答by Dhina k
Download "json simple 1.1 jar" from this https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=
从此https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=下载“json simple 1.1 jar”
And add the jar file to your lib folder
并将 jar 文件添加到您的 lib 文件夹中
using JSONValue you can convert LinkedHashMap to json string
使用 JSONValue 您可以将 LinkedHashMap 转换为 json 字符串
for more reference click here http://androiddhina.blogspot.in/2015/09/ordered-json-string-in-android.html
更多参考点击这里http://androiddhina.blogspot.in/2015/09/ordered-json-string-in-android.html
回答by UnixShadow
Real answer can be found in specification, json is unordered. However as a human reader I ordered my elements in order of importance. Not only is it a more logic way, it happened to be easier to read. Maybe the author of the specification never had to read JSON, I do.. So, Here comes a fix:
真正的答案可以在规范中找到,json 是无序的。然而,作为一个人类读者,我按重要性排序了我的元素。它不仅是一种更符合逻辑的方式,而且碰巧更容易阅读。也许规范的作者从来不需要阅读 JSON,我会阅读 .. 所以,这里有一个修复:
/**
* I got really tired of JSON rearranging added properties.
* Specification states:
* "An object is an unordered set of name/value pairs"
* StackOverflow states:
* As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit.
* I state:
* My implementation will freely arrange added properties, IN SEQUENCE ORDER!
* Why did I do it? Cause of readability of created JSON document!
*/
private static class OrderedJSONObjectFactory {
private static Logger log = Logger.getLogger(OrderedJSONObjectFactory.class.getName());
private static boolean setupDone = false;
private static Field JSONObjectMapField = null;
private static void setupFieldAccessor() {
if( !setupDone ) {
setupDone = true;
try {
JSONObjectMapField = JSONObject.class.getDeclaredField("map");
JSONObjectMapField.setAccessible(true);
} catch (NoSuchFieldException ignored) {
log.warning("JSONObject implementation has changed, returning unmodified instance");
}
}
}
private static JSONObject create() {
setupFieldAccessor();
JSONObject result = new JSONObject();
try {
if (JSONObjectMapField != null) {
JSONObjectMapField.set(result, new LinkedHashMap<>());
}
}catch (IllegalAccessException ignored) {}
return result;
}
}
回答by thyzz
u can retain the order, if u use JsonObject that belongs to com.google.gson :D
如果您使用属于 com.google.gson 的 JsonObject,您可以保留订单:D
JsonObject responseObj = new JsonObject();
responseObj.addProperty("userid", "User 1");
responseObj.addProperty("amount", "24.23");
responseObj.addProperty("success", "NO");
Usage of this JsonObject doesn't even bother using Map<>
这个 JsonObject 的用法甚至不用 Map<>
CHEERS!!!
干杯!!!
回答by tsohr
For those who're using maven, please try com.github.tsohr/json
对于那些使用 maven 的人,请尝试com.github.tsohr/json
<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
<groupId>com.github.tsohr</groupId>
<artifactId>json</artifactId>
<version>0.0.1</version>
</dependency>
It's forked from JSON-javabut switch its map implementation with LinkedHashMapwhich @lemiorhan noted above.
它是从JSON-java派生出来的,但使用@lemiorhan 上面提到的LinkedHashMap切换其地图实现。
回答by prachi
For Java code, Create a POJO class for your object instead of a JSONObject. and use JSONEncapsulator for your POJO class. that way order of elements depends on the order of getter setters in your POJO class. for eg. POJO class will be like
对于 Java 代码,为您的对象创建一个 POJO 类而不是 JSONObject。并为您的 POJO 类使用 JSONEncapsulator。这样元素的顺序取决于 POJO 类中 getter setter 的顺序。例如。POJO 类会像
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
以及您需要在何处发送 json 对象作为响应
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
此行的响应将是
{myObject : {//attributes order same as getter setter order.}}
{myObject : {//attributes order 与 getter setter order.}}