Jackson databind enum case insensitive

jackson case insensitive
java enum case insensitive
jackson enum deserialization
resttemplate case insensitive
jackson serialize an enum
jackson case object
kotlin jackson enum
com fasterxml jackson databind exc unrecognizedpropertyexception unrecognized field case sensitive

How can I deserialize JSON string that contains enum values that are case insensitive? (using Jackson Databind)

The JSON string:

[{"url": "foo", "type": "json"}]

and my Java POJO:

public static class Endpoint {

    public enum DataType {
        JSON, HTML
    }

    public String url;
    public DataType type;

    public Endpoint() {

    }

}

in this case,deserializing the JSON with "type":"json" would fail where as "type":"JSON" would work. But I want "json" to work as well for naming convention reasons.

Serializing the POJO also results in upper case "type":"JSON"

I thought of using @JsonCreator and @JsonGetter:

    @JsonCreator
    private Endpoint(@JsonProperty("name") String url, @JsonProperty("type") String type) {
        this.url = url;
        this.type = DataType.valueOf(type.toUpperCase());
    }

    //....
    @JsonGetter
    private String getType() {
        return type.name().toLowerCase();
    }

And it worked. But I was wondering whether there's a better solutuon because this looks like a hack to me.

I can also write a custom deserializer but I got many different POJOs that use enums and it would be hard to maintain.

Can anyone suggest a better way to serialize and deserialize enums with proper naming convention?

I don't want my enums in java to be lowercase!

Here is some test code that I used:

    String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
    Endpoint[] arr = new ObjectMapper().readValue(data, Endpoint[].class);
        System.out.println("POJO[]->" + Arrays.toString(arr));
        System.out.println("JSON ->" + new ObjectMapper().writeValueAsString(arr));

In version 2.4.0 you can register a custom serializer for all the Enum types (link to the github issue). Also you can replace the standard Enum deserializer on your own that will be aware about the Enum type. Here is an example:

public class JacksonEnum {

    public static enum DataType {
        JSON, HTML
    }

    public static void main(String[] args) throws IOException {
        List<DataType> types = Arrays.asList(JSON, HTML);
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                              final JavaType type,
                                                              BeanDescription beanDesc,
                                                              final JsonDeserializer<?> deserializer) {
                return new JsonDeserializer<Enum>() {
                    @Override
                    public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                        Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                        return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                    }
                };
            }
        });
        module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
            @Override
            public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                jgen.writeString(value.name().toLowerCase());
            }
        });
        mapper.registerModule(module);
        String json = mapper.writeValueAsString(types);
        System.out.println(json);
        List<DataType> types2 = mapper.readValue(json, new TypeReference<List<DataType>>() {});
        System.out.println(types2);
    }
}

Output:

["json","html"]
[JSON, HTML]

Case insensitive enum deserialization feature · Issue #1313 , Enums are only properly deserialized if the value is uppercase. We don't want to force all Skip to content. FasterXML / jackson-databind · Sign up Case insensitive enum deserialization feature #1313. Closed. yissachar  Problem is releated to com.fasterxml.jackson.databind.util.EnumResolver. it uses HashMap to hold enum values and HashMap doesn’t support case insensitive keys. in answers above, all chars should be uppercase or lowercase. but I fixed all (in)sensitive problems for enums with that:


Jackson 2.9

This is now very simple, using jackson-databind 2.9.0 and above

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);

// objectMapper now deserializes enums in a case-insensitive manner

Full example with tests

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

  private enum TestEnum { ONE }
  private static class TestObject { public TestEnum testEnum; }

  public static void main (String[] args) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);

    try {
      TestObject uppercase = 
        objectMapper.readValue("{ \"testEnum\": \"ONE\" }", TestObject.class);
      TestObject lowercase = 
        objectMapper.readValue("{ \"testEnum\": \"one\" }", TestObject.class);
      TestObject mixedcase = 
        objectMapper.readValue("{ \"testEnum\": \"oNe\" }", TestObject.class);

      if (uppercase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize uppercase value");
      if (lowercase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize lowercase value");
      if (mixedcase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize mixedcase value");

      System.out.println("Success: all deserializations worked");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Investigate issues with insensitive Jackson databind enums · Issue , should be configurable so that it can accept case insensitive enums. Following the answers and documentation of Jackson & Spring Boot the  Enums are only properly deserialized if the value is uppercase. We don't want to force all clients to have to manipulate their data into uppercase, so we would like to accept a String case-insensitively and have it be deserialized into the correct enum. Others have encountered this issue and there are various solutions for achieving this effect.


I ran into this same issue in my project, we decided to build our enums with a string key and use @JsonValue and a static constructor for serialization and deserialization respectively.

public enum DataType {
    JSON("json"), 
    HTML("html");

    private String key;

    DataType(String key) {
        this.key = key;
    }

    @JsonCreator
    public static DataType fromString(String key) {
        return key == null
                ? null
                : DataType.valueOf(key.toUpperCase());
    }

    @JsonValue
    public String getKey() {
        return key;
    }
}

Jackson databind enum case insensitive, How can I deserialize JSON string that contains enum values that are case insensitive? (using Jackson Databind). The JSON string: [{"url": "foo"  According this question and the answers, Jackson 2.9.* should be configurable so that it can accept case insensitive enums. Following the answers and documentation of Jackson & Spring Boot the below application.yaml file should be properly configuring Jackson to accept case insensitive enums. However it does not and results in the following


Since Jackson 2.6, you can simply do this:

    public enum DataType {
        @JsonProperty("json")
        JSON,
        @JsonProperty("html")
        HTML
    }

For a full example, see this gist.

MapperFeature (jackson-databind 2.9.1 API), Feature that determines if Enum deserialization should be case sensitive or not. ACCEPT_CASE_INSENSITIVE_PROPERTIES. Feature that will allow for more  Feature that determines if Enum deserialization should be case sensitive or not. If enabled, Enum deserialization will ignore case, that is, case of incoming String value and enum id (dependant on other settings, either `name()`, `toString()`, or explicit override) do not need to match. Feature is disabled by default.


I went for the solution of Sam B. but a simpler variant.

public enum Type {
    PIZZA, APPLE, PEAR, SOUP;

    @JsonCreator
    public static Type fromString(String key) {
        for(Type type : Type.values()) {
            if(type.name().equalsIgnoreCase(key)) {
                return type;
            }
        }
        return null;
    }
}

Jackson - Case insensitive deserialization, Jackson is a well-known library for JSON utilities. It has a wide area of features. One of them is case insensitive deserialization for field names. Problem is releated to com.fasterxml.jackson.databind.util.EnumResolver. it uses HashMap to hold enum values and HashMap doesn't support case insensitive keys. in answers above, all chars should be uppercase or lowercase. but I fixed all (in)sensitive problems for enums with that:


How To Serialize and Deserialize Enums with Jackson, How to serialize and deserialize an Enum as a JSON Object using Jackson 2. Representation. By default, Jackson will represent Java Enums as simple String – for example: ? In this case, the object is Distance.INCH: ? public static final MapperFeature ACCEPT_CASE_INSENSITIVE_PROPERTIES Feature that will allow for more forgiving deserialization of incoming JSON. If enabled, the bean properties will be matched using their lower-case equivalents, meaning that any case-combination (incoming and matching names are canonicalized by lower-casing) should work.


java - Jackson databind enum case insensitive, В версии 2.4.0 вы можете зарегистрировать собственный сериалайзер для всех типов Enum (link к вопросу GitHub). Также вы можете самостоятельно  One of the ConfigurationProperty I have in my ConfigurationSection is an ENUM. When .net parses this enum string value from the config file, an exception will be thrown if the case does not match exactly. Is there away to ignore case when parsing this value?


java, Jackson databind enum case insensitive. Come posso deserializzare la stringa JSON che contiene valori enum senza distinzione tra maiuscole e minuscole? I want to be able for jackson to parse case insensitive enums. For e.g. public enum OperType { SUM PRODUCT } i want to accept both "SUM" and "sum" in the POST request. I am getting hold of objectMapper in Application::run and enabling the setting: environment.getObjectMapper().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);