Does the sequence of the values matter in a JSON object?

My question is that does the order of the JSON object really matters on the server side?

It should not matter. According to various JSON specifications, the order of the attributes is not significant. For example:

“An object is an unordered set of name/value pairs.” (Source json.org)

“An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.” (Source 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?

With difficulty, I fear:

  • 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 – For example, the nitwits that this poor developer was working for … https://stackoverflow.com/a/4515863/139985

2 – RFC 7159 also says this: “JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software. Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences.“. By my reading, this recommends that JSON libraries should hide any order of the pairs from application code.

3 – JSON-simple : https://code.google.com/p/json-simple/. There could be others too.

Leave a Comment