Jackson数据绑定enum不区分大小写



如何反序列化包含不区分大小写的enum值的JSON字符串?(使用Jackson Databind)

JSON字符串:
[{"url": "foo", "type": "json"}]

和我的Java POJO:

public static class Endpoint {
    public enum DataType {
        JSON, HTML
    }
    public String url;
    public DataType type;
    public Endpoint() {
    }
}

在这种情况下,使用"type":"json"反序列化JSON将失败,而"type":"JSON"可以工作。但是出于命名约定的原因,我希望"json"也能工作。

序列化POJO也会产生大写的"type":"JSON"

我想使用@JsonCreator和@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();
    }

它起作用了。但我想知道是否有更好的解决方案,因为这看起来像一个黑客。

我也可以写一个自定义的反序列化器,但是我有很多不同的pojo使用枚举,这将很难维护。

有谁能提出一个更好的方法来序列化和反序列化具有正确命名约定的枚举吗?

我不希望我在java中的枚举是小写的!

下面是我使用的一些测试代码:
    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));

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

我在我的项目中遇到了同样的问题,我们决定用字符串键构建我们的枚举,并分别使用@JsonValue和静态构造函数进行序列化和反序列化。

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 2.6开始,您可以简单地这样做:

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

在2.4.0版本中,您可以为所有Enum类型注册自定义序列化器(链接到github问题)。此外,您还可以自己替换标准的Enum反序列化器,它将知道Enum类型。下面是一个例子:

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);
    }
}
输出:

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

如果你正在使用Spring Boot 2.1.x和Jackson 2.9,你可以简单地使用这个应用程序属性:

spring.jackson.mapper.accept-case-insensitive-enums=true

我选择了Sam b的解决方案但是是一个更简单的变体。

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

对于那些试图在GET参数中对Enum忽略大小写进行反序列化的人来说,启用ACCEPT_CASE_INSENSITIVE_ENUMS不会有任何好处。这没有帮助,因为这个选项只适用于体反序列化。不如试试这个:

public class StringToEnumConverter implements Converter<String, Modes> {
    @Override
    public Modes convert(String from) {
        return Modes.valueOf(from.toUpperCase());
    }
}

然后

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToEnumConverter());
    }
}

答案和代码示例来自这里

要允许jackson中枚举不区分大小写的反序列化,只需将以下属性添加到spring引导项目的application.properties文件中。

spring.jackson.mapper.accept-case-insensitive-enums=true

如果您有yaml版本的属性文件,请将以下属性添加到您的application.yml文件中。

spring:
  jackson:
    mapper:
      accept-case-insensitive-enums: true

向@Konstantin Zyubin道歉,他的回答接近我需要的-但我不理解,所以我认为应该这样做:

如果你想将一个枚举类型反序列化为不区分大小写——也就是说,你不想或不能修改整个应用程序的行为,你可以为一个类型创建一个自定义的反序列化器——通过子类化StdConverter,并强制Jackson使用JsonDeserialize注释只在相关字段上使用它。

的例子:

public class ColorHolder {
  public enum Color {
    RED, GREEN, BLUE
  }
  public static final class ColorParser extends StdConverter<String, Color> {
    @Override
    public Color convert(String value) {
      return Arrays.stream(Color.values())
        .filter(e -> e.getName().equalsIgnoreCase(value.trim()))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("Invalid value '" + value + "'"));
    }
  }
  @JsonDeserialize(converter = ColorParser.class)
  Color color;
}

问题与com.fasterxml.jackson. databindd .util. enumresolver有关。它使用HashMap来保存枚举值,HashMap不支持区分大小写的键。

在上面的答案

中,所有的字符都应该是大写或小写的。但我修复了所有(in)敏感问题的枚举:

https://gist.github.com/bhdrk/02307ba8066d26fa1537

CustomDeserializers.java

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.EnumDeserializer;
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
import com.fasterxml.jackson.databind.util.EnumResolver;
import java.util.HashMap;
import java.util.Map;

public class CustomDeserializers extends SimpleDeserializers {
    @Override
    @SuppressWarnings("unchecked")
    public JsonDeserializer<?> findEnumDeserializer(Class<?> type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException {
        return createDeserializer((Class<Enum>) type);
    }
    private <T extends Enum<T>> JsonDeserializer<?> createDeserializer(Class<T> enumCls) {
        T[] enumValues = enumCls.getEnumConstants();
        HashMap<String, T> map = createEnumValuesMap(enumValues);
        return new EnumDeserializer(new EnumCaseInsensitiveResolver<T>(enumCls, enumValues, map));
    }
    private <T extends Enum<T>> HashMap<String, T> createEnumValuesMap(T[] enumValues) {
        HashMap<String, T> map = new HashMap<String, T>();
        // from last to first, so that in case of duplicate values, first wins
        for (int i = enumValues.length; --i >= 0; ) {
            T e = enumValues[i];
            map.put(e.toString(), e);
        }
        return map;
    }
    public static class EnumCaseInsensitiveResolver<T extends Enum<T>> extends EnumResolver<T> {
        protected EnumCaseInsensitiveResolver(Class<T> enumClass, T[] enums, HashMap<String, T> map) {
            super(enumClass, enums, map);
        }
        @Override
        public T findEnum(String key) {
            for (Map.Entry<String, T> entry : _enumsById.entrySet()) {
                if (entry.getKey().equalsIgnoreCase(key)) { // magic line <--
                    return entry.getValue();
                }
            }
            return null;
        }
    }
}

用法:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class JSON {
    public static void main(String[] args) {
        SimpleModule enumModule = new SimpleModule();
        enumModule.setDeserializers(new CustomDeserializers());
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(enumModule);
    }
}

我使用了一个修改过的Iago Fernández和Paul的解决方案。

我在我的requestobject中有一个enum,它需要不区分大小写

@POST
public Response doSomePostAction(RequestObject object){
 //resource implementation
}

class RequestObject{
 //other params 
 MyEnumType myType;
 @JsonSetter
 public void setMyType(String type){
   myType = MyEnumType.valueOf(type.toUpperCase());
 }
 @JsonGetter
 public String getType(){
   return myType.toString();//this can change 
 }
}

当我想以不区分大小写的方式(基于问题中发布的代码)反序列化时,我有时是这样处理枚举的:

@JsonIgnore
public void setDataType(DataType dataType)
{
  type = dataType;
}
@JsonProperty
public void setDataType(String dataType)
{
  // Clean up/validate String however you want. I like
  // org.apache.commons.lang3.StringUtils.trimToEmpty
  String d = StringUtils.trimToEmpty(dataType).toUpperCase();
  setDataType(DataType.valueOf(d));
}

如果枚举是非平凡的,因此在它自己的类中,我通常添加一个静态解析方法来处理小写字符串。

用jackson反序列化enum很简单。当你想要反序列化基于String的enum时,需要一个构造函数,一个getter和一个setter到你的enum。此外,使用该enum的类必须有一个setter,该setter接收DataType作为参数,而不是String:

public class Endpoint {
     public enum DataType {
        JSON("json"), HTML("html");
        private String type;
        @JsonValue
        public String getDataType(){
           return type;
        }
        @JsonSetter
        public void setDataType(String t){
           type = t.toLowerCase();
        }
     }
     public String url;
     public DataType type;
     public Endpoint() {
     }
     public void setType(DataType dataType){
        type = dataType;
     }
}

当你有你的json,你可以反序列化到端点类使用ObjectMapper的Jackson:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
try {
    Endpoint endpoint = mapper.readValue("{"url":"foo","type":"json"}", Endpoint.class);
} catch (IOException e1) {
        // TODO Auto-generated catch block
    e1.printStackTrace();
}

最新更新