且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jackson 数据绑定枚举不区分大小写

更新时间:2023-01-16 09:58:21

Jackson 2.9

现在这个很简单,使用jackson-databind 2.9.0 及以上

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

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


带有测试的完整示例

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