Stanislav Ivanov Stanislav Ivanov - 3 months ago 23
Groovy Question

Does JsonOutput.toJson in groovy keeps the order of the properties?

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?

Answer

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.