jackson Spring boot 枚举类型不区分大小写映射

2018-03-09 13:19:10
2027次阅读
0个评论
允许客户端使用不区分大小写的枚举来创建请求对象。其他字段/属性可能需要区分大小写,但枚举不区分大小写。


参考类org.springframework.core.convert.support.StringToEnumConverterFactory,可以像这样自定义converterFactory



public class MyStringToEnumConverterFactory implements ConverterFactory<String, Enum> {

@Override
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
    return new StringToEnum(getEnumType(targetType));
}

private class StringToEnum<T extends Enum> implements Converter<String, T> {

    private final Class<T> enumType;

    public StringToEnum(Class<T> enumType) {
        this.enumType = enumType;
    }

    @Override
    public T convert(String source) {
        if (source.isEmpty()) {
            // It's an empty enum identifier: reset the enum value to null.
            return null;
        }

        return (T) Enum.valueOf(this.enumType, source.trim().toUpperCase());
    }
}

private static Class<?> getEnumType(Class targetType) {
    Class<?> enumType = targetType;
    while (enumType != null && !enumType.isEnum()) {
        enumType = enumType.getSuperclass();
    }
    if (enumType == null) {
        throw new IllegalArgumentException(
                "The target type " + targetType.getName() + " does not refer to an enum");
    }
    return enumType;
}
}



并添加到ConverterRegistry


@Configuration
public class MyConfiguration {

@Bean
public ConverterRegistry initConverter(ConverterRegistry registry) {
    registry.addConverterFactory(new MyStringToEnumConverterFactory());
    return registry;
}
}
收藏00

登录 后评论。没有帐号? 注册 一个。