1

I cannot see in the documentation about JsonOutput.toJson if it will keep the order of the properties we are sending. For example, the following code:

jsonResponse = JsonOutput.toJson([
    memberId:memberId,
    emailAddress: emailAddress
])

Can we rely on that we will always get a response where "memberId" will be first?

cfrick
  • 35,203
  • 6
  • 56
  • 68
Stanislav Ivanov
  • 425
  • 2
  • 7
  • 19
  • 2
    The json spec says that the order is not guaranteed http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order anything that requires a guaranteed order is broken by design – tim_yates Aug 09 '16 at 11:19
  • 1
    I am totally aware what the JSON spec says. That is why I am putting this question in relation specifically to groovy JsonOutput – Stanislav Ivanov Aug 09 '16 at 11:33
  • at best it could only keep the order of the ingoing data structure (LinkedHashMap in that case) and since the target format does not have order, you rely on an implementation detail. – cfrick Aug 09 '16 at 11:41
  • Ok, our client insists that we have the same order with every response. I am aware that it might be an implementation detail that we are relying on and that is why I am looking for a firm answer. Either yes or no so that we can take actions. – Stanislav Ivanov Aug 09 '16 at 11:52
  • then i'd say your best bet is to study the source code of `JsonOutput` for the version you are using and then write/generate alot of tests for when this "feature" is breaking. otherwise use key/value tuples in a list. – cfrick Aug 09 '16 at 12:06
  • 1
    But even if it maintains order now, I not sure any future versions are guaranteed to respect that order.... – tim_yates Aug 09 '16 at 13:55
  • While relying on ordering of maps is not a great idea it does make unit testing easier (don't need to redeclare things when making assertions). I just found out that changing from JDK 8 to JDK 11 changes map ordering and makes a bunch of tests fail. – tschumann Jun 24 '20 at 23:52

1 Answers1

1

I believe the order is not guaranteed.

Here is the source-code for groovy.json.JsonOutput in Groovy 2.4.4. From this code, the method toJson(Map m) calls writeMap(Map<?, ?> map, CharBuf buffer) which iterates over the entries of the map. This is likely the spot where the order may be lost.

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
  • Thanks, Michael. I saw the source yesterday, but I didnt have time to post it as well. Even though we get the same order, I agree that it is not reliable and not guaranteed. – Stanislav Ivanov Aug 10 '16 at 07:58