I'm trying to replace a custom JSON (de)serialization in a groovy/grails project with Jackson.
I'm having trouble getting Jackson to output a pretty-printed JSON with keys sorted in a simple 'natural' alphabetic order. I've tried this (and many variations):
mymap = [ ... ] // Some groovy map
def mapper = new ObjectMapper()
mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
def jsonstring = mapper.defaultPrettyPrintingWriter().writeValueAsString(mymap)
But Jackson stubbornly generates a JSON where the keys seem to be in a random order. I've tried changing the type of 'mymap' with a TreeMap, and in that case all keys are properly sorted as expected.
I'm wondering if there is a way to get the keys sorted without changing 'mymap' above to a TreeMap (and recursively all of its map values...).
SORT_PROPERTIES_ALPHABETICALLY seems to be intended to do precisely that, but it's not doing it for some reason. Would you know why that is? Anything I'm doing wrong above?
I've tried with Jackson 1.8.3, 1.8.8 and 1.9.5, same result (random keys).
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
Advertisements. let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class.
Jackson can serialize and deserialize polymorphic data structures very easily. The CarTransporter can itself carry another CarTransporter as a vehicle: that's where the tree structure is! Now, you know how to configure Jackson to serialize and deserialize objects being represented by their interface.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
As stated by @tim_yates, this doesn't work for map keys.
You could use
mapper.configure(SerializationConfig.Feature.ORDER_MAP_ENTRIES_BY_KEYS, true)
With newer version ( >= 2.6.1) the API changed to:
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With