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?