Search code examples
javaserializationjacksondeserializationtreemap

Serialize/Deserialize case insensitive map using jackson ObjectMapper


I am trying to use Jackson's ObjectMapper class to serialize an object that looks like this:

TreeMap<String, String> mappings = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

but when the object is serialized, it ends up looking like this:

{"mappings": {"key": "value"}}

When deserializing, it loses the case insensitive property of the map. Does anyone know how to resolve this, or possibly a type of case insensitive map class which I can use to serialize and deserialize? Is there a Jackson mapper property that I can use to fix this issue?

Here is some sample code:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.util.TreeMap;
    
    public class Main {
        public static void main(String[] args) throws JsonProcessingException {
            TreeMap<String, String> mappings = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
            mappings.put("Test3", "3");
            mappings.put("test1", "1");
            mappings.put("Test2", "2");
    
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mappings);
            System.out.println(json);
            
            TreeMap<String, String> deserMappings = objectMapper.readValue(json, TreeMap.class);
            
            System.out.println("Deserialized map case insensitive test: " + deserMappings.get("test3"));
        }
    }

And sample output:

    {
      "test1" : "1",
      "Test2" : "2",
      "Test3" : "3"
    }
    Deserialized map case insensitive test: null

Solution

  • I think you are misinterpreting the formatting parameter. It's describing a situation where you want to ignore case, which is what it's doing, ignoring the fact that you have key values starting with 'T' and 't'. It's treating them all as if they were the same case and putting them in order based on the rest of the string. The object call also allows you to define your own sorting comparator. You could just use this if you wanted to do something special.

    https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#TreeMap-java.util.Comparator-