I have a JSON object which I have constructed within my Java program.

JSONObject jObj = {"AAA:aaa","BBB:bbb","CCC:ccc"}

I am sending this object to a server in which it expects the JSON object in the following type.

{"BBB:bbb", "AAA:aaa", "CCC:ccc"}

My question is that does the order of the JSON object really matters on the server side? If yes, how can I change the order?

推荐答案

我的问题是,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.

Json相关问答推荐

将数据从嵌套的SON数组提取到更简单的数组中

JOLT规范:转移到现有数组

使用Jolt将字符串数组转换为JSON对象数组

如何在使用GO时检测JSON中不需要的字段?

在PowerShell中,如何获取数据对所在的JSON对象的名称

如何判断响应数组是否存在以及S是否有其他内容...?

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

删除 JOLT 中的方括号

使用带有逗号的字段名称构建 struct

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

JQuery,使用 GET 方法发送 JSON 对象

按 JSON 数据类型 postgres 排序

IE中Json响应下载(7~10)

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何使用 LWP 发出 JSON POST 请求?

使用 Node.js 对 JSON 中的字符串大小有限制吗?

在浏览器中查看 JSON 文件

JSON Schema:验证数字或空值

as_json 没有在关联上调用 as_json

设置对象不是 JSON 可序列化的