java-数据字典转换

Dict 字典注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Dict {
	
	/**
	 * 转换的类型
	 * content : 统计内容转换
	 */
	String type() default "";
	/**
	 * 1 : {"code":"code","name":"name"}  默认
	 * 2 : {"code":"name"}
	 */
	int trans() default 1;
	
}

BaseEnum 字典格式类

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class BaseEnum {
	
    private Object code;

    private String name;
}

DictJsonSerializer 字典转换实现类

import java.io.IOException;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class DictJsonSerializer extends JsonSerializer<Object> {
	
	@Override
    public void serialize(Object dictVal, JsonGenerator generator, SerializerProvider provider) throws IOException {
    	ObjectMapper objectMapper = new ObjectMapper();
    	StringBuffer dictValName = new StringBuffer("");
        String currentName = generator.getOutputContext().getCurrentName();
        // 定义转换类型
        int trans = 1;
        try {
        	// 获取字段
            Field field = generator.getCurrentValue().getClass().getDeclaredField(currentName);	
            // 获取字典属性
            Dict dict = field.getDeclaredAnnotation(Dict.class);
            if(dict == null) {
            	objectMapper.writeValue(generator, dictVal);
            	return;
            }
            // 获取字典type
            String type = dict.type();
            trans = dict.trans();
            if(type == null || StringUtils.isEmpty(type)) {
            	if(trans == 2) {
            		objectMapper.writeValue(generator, dictValName.toString());
            	}else {
            		objectMapper.writeValue(generator, BaseEnum.builder().code(dictVal).name(dictValName.toString()).build());
            	}
            	return;
            }
            // 通过字典key转换成获取字典value
            String val = dictVal == null ? "" : dictVal.toString();
            if(!StringUtils.isEmpty(val)) {
            	// 判断字典类型, 依据类型获取对应的value
            	if("content".equals(type)) {
            		dictValName = new StringBuffer(ContentCompare.getContentName(val));
            	} else {
            		// 支持key1,key2方式
            		String[] codes = val.split(",");
            		int size = codes.length;
					for (int i = 0; i < size; i++) {
                		Object valName = ParamCompareV1.param_compare_dict.get(codes[i]);
                		dictValName.append(valName == null ? "" : valName.toString());
                		if(i != size - 1) {
                			dictValName.append(",");
                		}
                	}
            	}
            }
            if(trans == 2) {
            	objectMapper.writeValue(generator, dictValName);
            } else {
            	objectMapper.writeValue(generator, BaseEnum.builder().code(dictVal).name(dictValName.toString()).build());
            }
        } catch (NoSuchFieldException e) {
        	log.error(e.getMessage());
        	if(trans == 2) {
        		objectMapper.writeValue(generator, dictValName);
        	}else {
        		objectMapper.writeValue(generator, BaseEnum.builder().code(dictVal).name(dictValName.toString()).build());
        	}
        }
    }
}

使用 BizRuleDto

import java.io.Serializable;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
 * 衍生规则表
 */
@SuppressWarnings("serial")
@Builder
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BizRuleDto implements Serializable{
	
	/**
	 * 自增id
	 */
	private Integer id;
	/**
	 * 唯一标识guid
	 */
	private String guid;
	/**
	 * 规则名称(中文) : 依据条件生成
	 */
	private String ruleName;
	/**
	 * 规则名称(英文) : 依据条件生成
	 */
	private String ruleCode;
	/**
	 * 类别
	 */
	private String category;
	/**
	 * 产品
	 */
	private String product;
	/**
	 * 统计内容
	 */
	@JsonSerialize(using = DictJsonSerializer.class)
	@Dict(type = "content")
	private String content;
	/**
	 * 时间维度
	 */
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "time")
	private String time;
	/**
	 * 统计方式
	 */
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "style")
	private String style;
	/**
	 * 参数1、2、3、4
	 */
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "param1")
	private String param1;
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "param2")
	private String param2;
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "param3")
	private String param3;
//	@JsonSerialize(using = DictJsonSerializer.class)
//	@Dict(type = "param4")
	private String param4;
	/**
	 * 状态
	 */
	private Integer state;
	/**
	 * 应生成变量个数
	 */
	private Integer paramSizeShould;
	/**
	 * 实际生成变量个数
	 */
	private Integer paramSizeReal;
	/**
	 * 创建时间
	 */
	private String createTime;
	
	private Integer edition;
	
}

如若不执行DictJsonSerializer, 则配置 :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.fintell.tools.GlobalThreadLocal;

import lombok.extern.slf4j.Slf4j;

/**
 * 返回RhCommonResponse时,设置reqId和时间
 */
@SuppressWarnings("rawtypes")
@ControllerAdvice
@Slf4j
public class ResponseControllerAdvice implements ResponseBodyAdvice<ResponseVo> {
	@Autowired
	private BizSecretService bizSecretService;
	
	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		// 只处理返回类型为RhCommonResponse
		if (returnType.getParameterType() == ResponseVo.class) {
			return true;
		}
		return false;
	}
	
	@Override
	public ResponseVo beforeBodyWrite(ResponseVo body, MethodParameter returnType, MediaType selectedContentType,
			Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		Long startTime = GlobalThreadLocal.reqStartTime.get();
		long costTime = (startTime == null ? 0 : System.currentTimeMillis() - startTime);
		log.info("[END] U:[{}] , T:[{}] , R:[{}]", request.getURI().toString(), costTime, JSON.toJSONString(body));
		return body;
	}
	
}

发布了67 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_17522211/article/details/105617440