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 + "]参数错误"); } } }
上一篇:WSL2-Ubuntu22.04-配置


下一篇:加密资产私钥安全完整手册(一) ,bitget钱包为例