Scala: Transforming JSON string to ListMap and preserving insertion order

Viewed 68

I have a JSON string that I am using within a Scala programme by converting it into a ListMap to perform some tests, and then returning the results in an output JSON, along with the original JSON as a value. I cannot use a schema as the JSONs are changeable. The original JSON string is for example:

 val originalJSONString =    
    {
        "outerKey1": "",
        "outerKey2": "",
        "outerKey3": {
            "innerKey1": "",
            "innerKey2": "",
            "innerKey3": ""
        }
    }

When I convert it to a ListMap using the below code, it will preserve the order of the outer keys, but not the inner keys as Object doesn't preserve the order.

val jsonListMap = mapper.readValue[ListMap[String, Object]](originalJSONString)

If I create a JSON that just contains the "outerKey3" key and its values, and the following code, it will preserve the order, but naturally will not work on the whole of the originalJSONString. The JSONs will always only have nesting of two levels.

val jsonListMap = mapper.readValue[ListMap[String, ListMap[String, String]]](originalJSONString)

There must surely be some way within this code to convert the keys with string values to Object/String and the keys with Map/ListMap values (i.e. outerKey3) to a ListMap? I want it to infer which data type it should be creating.

I was thinking about creating a function, or using Either/Option but I'm not sure these are appropriate.

(I am aware that JSON is by definition unordered and Scala/Java do not preserve order for this reason. Unfortunately without being able to convert the necessary values to ListMap the final JSON is unordered and the humans who will be reading it - not querying it - want it in order. I do not want to return the original string as the formatting would make my querying of the output JSON a nightmare. Also I would like to know if inferring data type in this way is possible for many other data wrangling issues outside of preserving JSON key order!)

Thank you in advance!

0 Answers
Related