Jackson Object mapper for converting java map to json supporting key order

I am using an API jackson.map.ObjectMapperto convert a map to a json string. For this, I use the writeValueAsString method.

I pass a map sorted by value before the method writeValueAsString. The JSON string I get is used based on keys.

Is there a way to convert maps to a JSON string using jackson without disturbing the order of the elements on the map.

I tried to set Feature.SORT_PROPERTIES_ALPHABETICALLYto false, but according to the documentation it is applicable only for POJO types.

Any idea to implement the specified behavior.

+4
source share
1 answer

Jackson 2.3.1 ( ) SortedMap, TreeMap, .

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));


}

: `

{
  "aaa" : "AAA",
  "ddd" : "DDD",
  "ccc" : "CCC",
  "bbb" : "BBB"
}

SortedMap

{
  "aaa" : "AAA",
  "bbb" : "BBB",
  "ccc" : "CCC",
  "ddd" : "DDD"
}

`

, TreeMap . Comparator treeMap .

: Jackson LinkedHashMap(), SortedMap. , , . , .

+9

Source: https://habr.com/ru/post/1527280/


All Articles