简介
本文介绍如何解决Java的SpringBoot中空字符串转枚举时报错的问题。
问题复现
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type *.**.**.PayType from String “”: value not one of declared Enum instance names: [ALIPAY, WECHAT_PAY, BANK_UNION]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type *.**.**.PayType from String “”: value not one of declared Enum instance names: [ALIPAY, WECHAT_PAY, BANK_UNION]
原因分析
字符串与枚举类的对应关系是:字符串对应枚举类的字面量(或者说name()方法);null对应null,如果是空字符串,会找不到对应的枚举类,就会报错。
解决方案
方案1:空字符串转null
@Configuration public class JackSonConfig { @Bean public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder, JacksonProperties jacksonProperties) { ObjectMapper objectMapper = builder.build(); // 将不匹配的enum转为null,防止报错 objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); return objectMapper; } }
修改后,这些数据都会对应null枚举类:null、空字符串、不匹配的任意字符串。
方案2:空字符串转特定枚举成员
枚举对应默认值上添加注解 @JsonEnumDefaultValue
@Configuration public class JackSonConfig { @Bean public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder, JacksonProperties jacksonProperties) { ObjectMapper objectMapper = builder.build(); // 将不匹配的enum转为默认值,防止报错 objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true); return objectMapper; } }
修改后,这些数据都会对应则使用添加@JsonEnumDefaultValue注解的枚举值:空字符串、不匹配的任意字符串。
请先
!