java-JSON顺序混合了
尝试使我的页面按我想要的顺序打印出JSONObject时遇到问题。 在我的代码中,我输入了以下内容:
JSONObject myObject = new JSONObject();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
但是,当我看到页面上的显示时,它显示:
JSON格式的字符串:.append
我需要按用户ID,数量和成功的顺序排列。 已经尝试在代码中重新排序,但无济于事。 我也尝试了.append ....这里需要一些帮助,谢谢!!
JSON guy asked 2019-12-28T12:03:46Z
12个解决方案
97 votes
您不能也不应该依赖JSON对象中元素的顺序。
来自[http://www.json.org/]的JSON规范
一个对象是一组无序的 名称/值对
作为结果,JSON库可以自由地按自己认为合适的方式重新排列元素的顺序。这不是错误。
Adrian Smith answered 2019-12-28T12:04:08Z
12 votes
我同意其他答案。 您不能依赖JSON元素的顺序。
但是,如果我们需要有序的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)
}
通常情况下,以下顺序不会保留。
@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)
}
您也可以查看我的帖子:[http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html]
lemiorhan answered 2019-12-28T12:04:41Z
5 votes
来自lemiorhan的例子我可以通过更改lemiorhan的代码行来解决采用:
JSONObject json = new JSONObject(obj);
代替这个:
JSONObject json = (JSONObject) obj
所以在我的测试代码中是:
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());
sang answered 2019-12-28T12:05:10Z
3 votes
真正的答案可以在规范中找到,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;
}
}
UnixShadow answered 2019-12-28T12:05:30Z
3 votes
这里的主要目的是发送一个有序的JSON对象作为响应。 我们不需要javax.json.JsonObject来实现。 我们可以将有序的json创建为字符串。首先以所需顺序创建一个具有所有键值对的LinkedHashMap。 然后生成字符串形式的json,如下所示。使用Java 8更加容易。
public Response getJSONResponse() {
Map linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A", "1");
linkedHashMap.put("B", "2");
linkedHashMap.put("C", "3");
String jsonStr = linkedHashMap.entrySet().stream()
.map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
.collect(Collectors.joining(",", "{", "}"));
return Response.ok(jsonStr).build();
}
该函数返回的响应如下:{"A":"1","B":"2","C":"3"}
Joy Banerjee answered 2019-12-28T12:05:55Z
2 votes
JavaScript对象和JSON无法设置键的顺序。 您可能会用Java正确地做到这一点(实际上我不知道Java对象是如何工作的),但是如果将它用于Web客户端或JSON的另一个使用者,则不能保证键的顺序。
Mark Snidovich answered 2019-12-28T12:06:15Z
2 votes
从此[https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=]下载“ json简单1.1 jar”
并将jar文件添加到您的lib文件夹中
使用JSONValue可以将LinkedHashMap转换为json字符串
有关更多参考,请单击此处[http://androiddhina.blogspot.in/2015/09/ordered-json-string-in-android.html]
Dhina k answered 2019-12-28T12:06:49Z
1 votes
如果您使用属于com.google.gson的JsonObject,则可以保留顺序:D
JsonObject responseObj = new JsonObject();
responseObj.addProperty("userid", "User 1");
responseObj.addProperty("amount", "24.23");
responseObj.addProperty("success", "NO");
使用Map <>甚至不用理会这个JsonObject的用法
干杯!!!
thyzz answered 2019-12-28T12:07:18Z
0 votes
就像所有人都告诉您的那样,JSON不会维护“序列”,而数组会维护“序列”,也许这可以说服您:订购的JSONObject
Kartikya answered 2019-12-28T12:07:38Z
0 votes
对于那些正在使用Maven的人,请尝试com.github.tsohr / json
com.github.tsohr
json
0.0.1
它是从JSON-java派生出来的,但是使用上面@lemiorhan指出的LinkedHashMap切换了其地图实现。
tsohr answered 2019-12-28T12:08:03Z
0 votes
对于Java代码,请为您的对象而不是JSONObject创建POJO类。并为您的POJO类使用JSONEncapsulator。这种方式的元素顺序取决于POJO类中的getter设置方法的顺序。例如 POJO类会像
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
以及您需要在哪里发送json对象作为响应
JSONContentEncapsulator JSONObject = new JSONEncapsulator("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
该行的响应将是
{myObject:{//属性顺序与getter setter顺序相同。}}
prachi answered 2019-12-28T12:08:36Z
0 votes
Underscore-java使用linkedhashmap存储JSON的键/值。
Valentyn Kolesnikov answered 2019-12-28T12:08:56Z