我的问题是,JSON对象的顺序在服务器端真的很重要吗?
这should not件事很重要.根据各种JSON规范,属性的顺序并不重要.例如:
"对象是一组无序的名称/值对."(来源json.org)
对象是零个或多个名称/值对的无序集合,其中名称是字符串,值是字符串、数字、布尔值、null、对象或数组(来源RFC 7159)
Unfortunately, there are nitwits out there1 who ignore that aspect of the specs, and place some significance on the order of the attributes. (The mistake is usually made when there is a disconnect between the people specifying the APIs and those implementing them, and the people doing the specification work don't really understand JSON.)
Fortunately, the chances are that whoever designed / implemented the server didn't make that mistake. Most Java JSON parsers I've come across don't preserve the attribute order when parsing ... by default2. It would be hard to accidentally implement a server where the order of the JSON attributes being parsed was significant.
If yes, how can i change the order?
在困难的情况下,我担心:
- You could generate the JSON by hand.
- There is at least one JSON for java implementation3 that allows you to supply the
Map
object that holds a JSON object's attributes. If you use a LinkedHashMap
or TreeMap
, it should retain the insertion order or the lexical order of the attribute keys.
1-例如,这个可怜的开发者为之工作的傻瓜...https://stackoverflow.com/a/4515863/139985
2-RFC 7159也这样说:"人们观察到JSON解析库在是否使调用软件的对象成员的顺序可见方面存在差异.Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences.".据我所知,这建议JSON库should对应用程序代码隐藏对的任何顺序
3 - JSON-simple : https://code.google.com/p/json-simple/. There could be others too.