Search code examples
jsonsortinggroovypretty-print

groovy JSON pretty string do not sort


Is it possible to stop groovy not to sort the JSON string while it call pretty string?

There is a program written which read JSON string from a file, make some changes to the JSON string and writing it back to file.

JSON string example

{
    "Obj1": [
        {
            "Val3": "CCIPDS",
            "Val1": [
            {
                "tn4": "111",
                "tn1": "222",
                "moretn": [
                {
                    "c6": "ch_ssn",
                    "b5": "ssn"
                }
                ]
            }
            ]
        }
    ]
}

Problem is when it write back to file, it changes the order of tags as follows using this code to write back

File jsonFile = new File('JsonFile.json')
String newJson = new JsonBuilder(jsonStringToWrite).toPrettyString()
jsonFile.withWriter('UTF-8')
{ 
    it << newJson 
}

and string updated as follows

{
    "Obj1": [
        {      
            "Val1": [
            {
                "tn1": "222",
                "tn4": "111",          
                "moretn": [
            {
                "b5": "ssn",
                "c6": "ch_ssn"              
            }
          ]
        }
        ],
        "Val3": "CCIPDS",
        }
    ]
}

Its needed to stop sorting.


Solution

  • tim_yates mentioned this in the comment, but I'll reiterate here and offer a bit of explaination. JSON Objects are unordered, Array are ordered. This is how it works with most languages/libraries, including Javascript. Groovy's JsonSlurper and JsonBuilder classes use Maps and Lists to represent JSON Objects and Arrays, respectively. Quoting the Javadocs for the Map Interface:

    The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

    I would suggest that your application not depend on the ordering of keys in JSON. Even if you get the ordering to be deterministic, it will likely result in code that is difficult to read and maintain. If you need something to be ordered, consider putting it in a JSON Array instead.