8

I use Jackson 2.5.0. I would like to write a method which takes arbitrary JSON-string and sorts every property by key alphabetically with Jackson. Including nested ones.

I learned there is a SORT_PROPERTIES_ALPHABETICALLY feature of Jackson's ObjectMapper which I wanted to use in order to achieve my goal. So my initial code based on this idea is:

class FooBar {
    String foo
    String bar
}

def sortFields(String source) {
    def om = new ObjectMapper().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)

    def obj = om.readValue(source, Map.class)
    return om.writeValueAsString(obj)
}

println sortFields('{"foo":"f","bar":"b"}')

Notice that I can't know ahead what structure input JSON has so Jackson unmarshalls it as a Map by default (LinkedHashMap to be more precise). I expected it to output a string with keys sorted alphabetically:

{"bar":"b","foo":"f"}

Unfortunately with the snippet above SORT_PROPERTIES_ALPHABETICALLY does not work when object to serialize is a Map. If I replace Map.class with FooBar.class my JSON properties will be sorted as expected. But as I said, I can't know ahead a type of input JSON and have a class in my code for any type possible. What other options do I have with Jackson?

Kirill
  • 6,762
  • 4
  • 51
  • 81

1 Answers1

4

This works for the top level map:

objectMapper.configure(
    SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true
);

Sadly it doesn't sort keys in any potential nested map you may have.

  • Looks like this is the solution. For me with Jackson 2.9.7 it worked for nested maps too, thank you! – Kirill Dec 12 '18 at 13:50
  • 2.9.8 here and it doesn't seem to sort my nested keys fwiw – Mat Schaffer Mar 08 '19 at 04:27
  • This is now [deprecated since 2.13](https://github.com/FasterXML/jackson-databind/blob/967ddd117f6114313df17169a0ed085ef8e3428e/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java#L2480) – Frederic Sep 15 '22 at 16:13