背景在前后端接口交互中,经常会出现一些枚举值,比如订单状态。前端请求参数一般都是整数值。相应的,后端接收参数也是使用int类型,然后转换为对应的枚举类型。每次都手动转换有点麻烦。有什么办法可以自动将接收到的int值转换成我想要的枚举值吗?实现定义了一个接口,表示可以使用int获取枚举类型的代码:publicinterfaceCodeEnum{intgetCode();}定义了枚举类,并实现了这个接口:publicenumDirectionimplementsCodeEnum{NORTH(0),东(1),南(2),西(3);方向(intcode){this.code=code;}私有最终代码;@OverridepublicintgetCode(){返回代码;}}定义一个反序列化类,继承JsonDeserializer,实现ContextualDeserializer接口JsonDeserializer:用于自定义反序列化器,将JSON字段值反序列化成我们想要的类型,这里需要将int表示的枚举值反序列化成具体的枚举enumerationclassValueContextualDeserializer:用于获取反序列化字段的类型@Slf4jpublicclassCodeEnumDeserializerextendsJsonDeserializerimplementsContextualDeserializer{privateClasspropertyClass;//记录枚举字段的类,用于获取其定义的所有枚举值publicCodeEnumDeserializer(){log.info("Constructwithnoargs");//必须没有参数构造函数,spring会调用}publicCodeEnumDeserializer(ClasspropertyClass){this.propertyClass=propertyClass;}@OverridepublicCodeEnumdeserialize(JsonParserp,DeserializationContextctxt)throwsIOException,JacksonException{intcode;尝试{code=p.getIntValue();}catch(JsonParseExceptione){返回null;}log.info("枚举代码:{}",code);returnArrays.stream(propertyClass.getEnumConstants())//调用Class的这个方法,获取枚举类的所有枚举值.filter(e->e.getCode()==code).findAny().orElseThrow(()->newIllegalArgumentException("没有这样的代码"+propertyClass.getSimpleName()));}@SuppressWarnings({"unchecked"})@OverridepublicJsonDeserializer>createContextual(DeserializationContextctxt,BeanPropertyproperty)throwsJsonMappingException{log.info("Constructwithpropertyclass");返回新的CodeEnumDeserializer((类&l吨;?扩展CodeEnum>)property.getType().getRawClass());//获取枚举字段的类型Class}}接收请求的类定义:@DatapublicclassTestReq{privateStringname;@JsonDeserialize(using=CodeEnumDeserializer.class)//为字段指定定义的反序列化器privateDirectiondirection;}也可以使用@JsonComponent注解进行全局配置,只需在CodeEnumDeserializer类中添加@JsonComponent即可(参考:使用@JsonComponent在SpringBoot中)