Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Object mapper to convert java map to json maintaining order of keys

Tags:

java

json

jackson

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.

like image 845
Ani Avatar asked Feb 17 '14 09:02

Ani


1 Answers

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.

like image 148
pdem Avatar answered Sep 20 '22 14:09

pdem