actual combat 23 —— 通过序列化对字典字段生成字典str字段和对应字典标签值

  • 注解:@JsonSerialize(using = DictSerializer.class)
package com.zyjk.common.core.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.zyjk.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyjk.common.core.annotation.DictType;
import com.zyjk.common.core.utils.DictUtils;

import java.io.IOException;
import java.util.Objects;

public class DictSerializer extends JsonSerializer<Object> implements ContextualSerializer {
    private final Logger log = LoggerFactory.getLogger(DictSerializer.class);

    /**
     * 生成序列化字段后缀
     */
    private static final String LABEL_SUFFIX = "Str";
    /**
     * 字典配置信息
     */
    private DictType dictType;

    public DictSerializer() {
        super();
    }

    public DictSerializer(DictType dictType) {
        this.dictType = dictType;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
        DictType dictAnno = property.getAnnotation(DictType.class);
        return new DictSerializer(dictAnno);
    }

    @Override
    public void serialize(Object value, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        serializerProvider.defaultSerializeValue(value, generator);
        String fieldName = generator.getOutputContext().getCurrentName();
        generator.writeStringField(fieldName.concat(LABEL_SUFFIX), value != null ? this.getDictLabel(dictType, value) : null);
    }

    /**
     * 获取字典信息
     *
     * @param dictType 字典类型
     * @param value    字典值
     * @return 字典标签
     */
    private String getDictLabel(DictType dictType, Object value) {
        try {
            String propertyValue = Objects.toString(value);
            if(StringUtils.isNotEmpty(dictType.readConverterExp())){
                return convertByExp(propertyValue,dictType.readConverterExp(),null);
            }
            String[] values = propertyValue.split(",");
            String label = null;
            for(String var : values){
                if (StringUtils.isNotEmpty(var)){
                    if (label == null) {
                        label = DictUtils.getDictLabel(dictType.value(), var);
                    } else {
                        label  += "," + DictUtils.getDictLabel(dictType.value(), var);
                    }
                } else {
                    if (label == null) {
                        label = "";
                    }
                }
            }
            return label;
        } catch (Exception e) {
            log.error("字典转换:获取字典描述异常,使用默认值:{},key:{}, dict:{}, 异常:{}", dictType.defaultValue(), value, dictType.value(), e.getMessage());
            return dictType.defaultValue();
        }
    }



    /**
     * 解析导出值 0=男,1=女,2=未知
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @param separator     分隔符
     * @return 解析后值
     */
    private String convertByExp(String propertyValue, String converterExp, String separator) {
        StringBuilder propertyString = new StringBuilder();
        String[] convertSource = converterExp.split(",");
        for (String item : convertSource) {
            String[] itemArray = item.split("=");
            if (StringUtils.isNotEmpty(separator) && StringUtils.containsAny(separator, propertyValue)) {
                for (String value : propertyValue.split(separator)) {
                    if (itemArray[0].equals(value)) {
                        propertyString.append(itemArray[1]).append(separator);
                        break;
                    }
                }
            } else {
                if (itemArray[0].equals(propertyValue)) {
                    return itemArray[1];
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
}
  • 注解:@DictType
package com.zyjk.common.core.annotation;

import java.lang.annotation.*;

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DictType {
    /** 字典类型 */
    String value() default "";

    /** 未查到字典值时的默认值 */
    String defaultValue() default "";

    /**
     * 读取内容转表达式 (如: 0=男,1=女,2=未知)
     */
    String readConverterExp() default "";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值