枚举规范接口类
所有的枚举类都实现该接口,统一规范
public interface BaseEnum {
/**
* 获取实际的值
* Jackson 在反序列化的时候会根据 value 进行反序列化,所以不用自定义反序列化规则
*
* @return value
*/
int getValue();
/**
* 获取对应的描述
*
* @return desc
*/
String getDesc();
}
Jackson 序列化
创建序列化类
public class BaseEnumSerializer extends JsonSerializer<BaseEnum> {
/**
* 缓存
*/
private static final Map<BaseEnum, Map<String, Object>> CACHE = new HashMap<>();
@Override
public void serialize(BaseEnum baseEnum, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (baseEnum == null) {
gen.writeObject(MapUtils.EMPTY_SORTED_MAP);
return;
}
Map<String, Object> result = Optional.ofNullable(CACHE.get(baseEnum)).orElseGet(() -> {
HashMap<String, Object> map = new HashMap<>(2);
map.put("value", baseEnum.getValue());
map.put("desc", baseEnum.getDesc());
CACHE.put(baseEnum, map);
return map;
});
gen.writeObject(result);
}
@Override
public Class<BaseEnum> handledType() {
return BaseEnum.class;
}
}
Spring Boot Jackson 配置
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer objectMapperBuilderCustomizer() {
return objectMapperBuilder -> objectMapperBuilder
.serializers(new BaseEnumSerializer());
}
}
Jackson 反序列化
在枚举类中定义一个静态方法用于返回枚举值,并使用JsonCreator
注解标识
示例:
@JsonCreator
public static BaseEnum getItem(String value){
// 根据 value 返回具体的枚举值
return null;
}
Spring MVC 使用枚举传参
创建 ConverterFactory 和 Convert
public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToEnumConverter<>(targetType);
}
private static class StringToEnumConverter<T extends BaseEnum> implements Converter<String, T> {
private Map<String, T> enumMap = Maps.newHashMap();
public StringToEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for (T e : enums) {
enumMap.put(e.getValue() + "", e);
}
}
@Override
public T convert(String source) {
T t = enumMap.get(source);
if (ObjectUtil.isNull(t)) {
throw new IllegalArgumentException("无法匹配对应的枚举值");
}
return t;
}
}
}
Mybatis Plus 使用枚举
https://mybatis.plus/guide/enum.html
通用 Mapper 使用枚举
https://github.com/abel533/Mapper/wiki/7.2.typehandler
写的不好,仅供参考