Jackson object mapper converts Java maps into JSON maintenance keys

I use Jackson map. The objectmapper API converts a map into a JSON string I use the writevalueasstring method to achieve this

I passed a value - based map to the writevalueasstring method The JSON string I get is key - based

Is there a way to use Jackson to convert a map to a JSON string without disturbing the order of items in the map

I try to add feature soRT_ PROPERTIES_ Alphabetally is set to false, but according to the documentation, it is only applicable to POJO types

Any idea to achieve the above behavior

Solution

Use Jackson 2.3 1 (I don't know the previous version) you can serialize a SortedMap, such as a treemap, and the command will be respected

Here is an example of 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));


}

This is the result:`

Use map

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

Using SortedMap

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

`

Edit: even if this is not SortedMap, it can use LinkedHashMap () on Jackson This is an implementation of map, which saves the order in which keys are inserted into the map This may be what you are looking for

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>