I am using jackson.map.ObjectMapper
API to convert map to json string. I am using writeValueAsString method to achieve this.
I pass a map sorted on the basis of values to writeValueAsString
method. The JSON string which I get is resorted on the basis of keys.
Is there a way to convert maps to JSON string using jackson without disturbing the order of items in the map.
I tried setting Feature.SORT_PROPERTIES_ALPHABETICALLY
to false, but as per documentation it is applicable only for POJO types.
Any idea to implement the said behavior.
with Jackson 2.3.1 (don't know for previous versions) you can serialize a SortedMap, for example a TreeMap, the order will be respected.
Here is an exempale in junit 4:
@Test
public void testSerialize() throws JsonProcessingException{
ObjectMapper om = new ObjectMapper();
om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES,false);
om.configure(SerializationFeature.INDENT_OUTPUT,true);
om.setSerializationInclusion(Include.NON_NULL);
SortedMap<String,String> sortedMap = new TreeMap<String,String>();
Map<String,String> map = new HashMap<String,String>();
map.put("aaa","AAA");
map.put("bbb","BBB");
map.put("ccc","CCC");
map.put("ddd","DDD");
sortedMap.putAll(map);
System.out.println(om.writeValueAsString(map));
System.out.println(om.writeValueAsString(sortedMap));
}
and here is the result:`
with a Map
{
"aaa" : "AAA",
"ddd" : "DDD",
"ccc" : "CCC",
"bbb" : "BBB"
}
with a SortedMap
{
"aaa" : "AAA",
"bbb" : "BBB",
"ccc" : "CCC",
"ddd" : "DDD"
}
`
The 1st serialization with a Map will not be ordered, The second one with a TreeMap will be ordered alphabeticaly using keys. you can pass a Comparator to the treeMap for a different order.
Edit: It also work on Jackson with a LinkedHashMap() even if this is not a SortedMap. This is an implementation of Map that keep the order which keys were inserted into the map. This could be what your are looking for.
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