SpringMVC枚举类型字段处理
public class EnumDeserializer extends JsonDeserializer<BaseEnum> {
/**
* 根据参数值获取对应的枚举
* @throws IOException
* @throws JacksonException
*/
@Override
public BaseEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
// 当前值
final String paramValue = p.getText();
//获取序列化信息
final JsonStreamContext parsingContext = p.getParsingContext();
// 获取当前序列化的类的对象
final Object currentValue = parsingContext.getCurrentValue();
//获取当前序列化的字段名
final String currentName = parsingContext.getCurrentName();
try {
// 反射获取当前序列化字段信息
final Field declaredField = currentValue.getClass().getDeclaredField(currentName);
// 通过字段信息获取对应的枚举的Class
final Class<BaseEnum> targetType = (Class<BaseEnum>) declaredField.getType();
//根据参数值获取对应的枚举
BaseEnum baseEnum = BaseEnum.getEnumByCode(targetType, paramValue);
if (ObjectUtil.isEmpty(baseEnum)) {
throw new RuntimeException("[" + currentName + "]参数错误");
}
//返回枚举
return baseEnum;
} catch (NoSuchFieldException e) {
throw new RuntimeException("[" + currentName + "]参数错误");
}
}
}