[英]How allow case-insensitive mapping of enums in jackson/Spring boot?
注意:這不是重復的。 另一個問題與 Spring 請求參數的自動編組無關。 它有一個解決方案,您可以使用 jackson 手動編組對象。
我想允許開發人員使用可以不區分大小寫的枚舉創建請求對象。 其他字段/屬性可能需要區分大小寫的匹配,但枚舉應該不區分大小寫。
到目前為止,我發現的唯一方法( initBinding
)要求您在編譯時指定確切的枚舉類。 我正在尋找一種更通用的方法來將 JSON 請求中的字符串編組為枚舉。
我發現的唯一當前方法:
@RestController
public class TestController
{
//...elided...
@InitBinder
public void initBinder(final WebDataBinder webdataBinder)
{
webdataBinder.registerCustomEditor( MyEnum.class, new CaseInsensitiveEnumConverter() );
}
}
但這需要使用已知的枚舉進行編譯。
你可以看到類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;
}
}
希望能幫到你!
從 spring 2.0 開始,在application.properties
設置以下內容就足夠了:
spring.jackson.mapper.accept-case-insensitive-enums = true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.