欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 枚举转换 博客分类: Java  

程序员文章站 2024-03-19 10:21:04
...

1、所有枚举使用实现一个通用接口

例如:

public interface BaseEnum {
    Integer getCode() ;
    String getMessage() ;
}

枚举定义:

public enum SexType  implements  BaseEnum{
   MEN(1, "男"), WOMAN(2, "女"), NONE(0, "未知");
   private int code;
   private String text;
SexType(int code, String text) {
      this.code = code;
      this.text = text;
}

   public Integer getCode() {
      return code;
}

   public String getMessage() {
      return text;
}
}

 

2、定义枚举转换工厂

public class EnumConverterFactory  implements ConverterFactory<String,BaseEnum> {

    private static final Map<Class, Converter> converterMap = new WeakHashMap<>();
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter result = converterMap.get(targetType);
        if(result == null) {
            result = new ConverterToEnum<>(targetType);
converterMap.put(targetType, result);
}
        return result;
}
    class ConverterToEnum<T extends BaseEnum> implements Converter<String, T> {
        private final Class<T> enumType;
        private Map<String, T> enumMap = new HashMap<>();
        public ConverterToEnum(Class<T> enumType) {
            this.enumType = enumType;
T[] enums = enumType.getEnumConstants();
            for(T e : enums) {
                enumMap.put(e.getCode() + "", e);
}
        }


        @Override
public T convert(String source) {
            T result = enumMap.get(source);
            if(result == null) {
                throw new IllegalArgumentException("No element matches " + source);
}
            return result;
}
    }

}

 

4、注册到spring boot

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

    @Override
public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new EnumConverterFactory());
}
}

 

 

5、spring boot json 响应code转换

import com.bjike.utils.EnumTools;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.math.NumberUtils;
import java.io.IOException;
@SuppressWarnings({ "rawtypes" })
public class EnumJsonSerializer extends JsonSerializer<Enum> {

   @Override
public void serialize(Enum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
      if (null == value) {
         return;
}
      int code = NumberUtils.toInt(EnumTools.getInvokeValue(value, "getCode"));
      if (code == -1) {
         code = value.ordinal();
}
      gen.writeString(String.valueOf(code));
}

}

MyWebAppConfigurer 类中,新增实现方法

 

/**
 * 新增枚举转换器
 * json返回枚举数字
 * */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
ObjectMapper objectMapper = builder.build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Enum.class, new EnumJsonSerializer());
objectMapper.registerModule(simpleModule);
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));}

 

枚举反射类:EnumTools 

 

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.reflect.MethodUtils;

import java.lang.reflect.Method;
import java.util.*;

public class EnumTools {
   
   public static String getText(Class<?> ref , Object code){
      return parseEumn(ref).get( String.valueOf(code) ) ;
}

   public static <T> T parseToEumn(Class<T> ref , Integer data){

      if(data == null){return null;}

      T[] ts = ref.getEnumConstants() ;
      for(T t : ts){
         Enum<?> tempEnum = (Enum<?>) t ;
         int code = NumberUtils.toInt(getInvokeValue(t, "getCode") , -1);
         if(code == -1){
            code = tempEnum.ordinal() ;
}
         if(code == data){
            return t ;
}
      }
      return null ;
}
   
   public static <T> Map<String, String> parseEumn(Class<T> ref){
      Map<String, String> map = new LinkedHashMap<>() ;
      if(ref.isEnum()){
         T[] ts = ref.getEnumConstants() ; 
         for(T t : ts){
            String text = getInvokeValue(t, "getMessage") ;
Enum<?> tempEnum = (Enum<?>) t ;
            if(text == null){
               text = tempEnum.name() ;
}
            String code = getInvokeValue(t, "getCode") ; 
            if(code == null){
               code = String.valueOf( tempEnum.ordinal() );
}
            map.put(code , text ) ; 
}
      }
      return map ;
}
   
   public static <T> String getInvokeValue(T t , String methodName){
      try {
         Method method = MethodUtils.getAccessibleMethod( t.getClass() , methodName);
String text = String.valueOf(method.invoke( t )) ;
         return text ;
} catch (Exception e) {
         return null ;
}
   }

}