@Dict 注解尝试

@Dict注解使用

@Dict注解主要是实现 字符的转换,给前端提供想要的数据。

annotation代码
package xx.xx.annotation;
import xx.xx.serialize.DictSerialize;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD})
@JsonSerialize(using = DictSerialize.class)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
public @interface Dict {
	String type() default "";
}

serialize包里面DictSerialize代码
Dict注解参数 type和name
在使用的时候会提供给前端value和label两个参数数据

package xx.xx.serialize;
import xx.xx.annotation.Dict;
import xx.xx.utils.CacheUtils;
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 java.io.IOException;

public class DictSerialize<T> extends JsonSerializer<T> implements ContextualSerializer {
	String type = "";
	String name = "";
	public void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
		if (value != null) {
			gen.writeStartObject();
			String info = CacheUtils.getDictInfo(this.type, String.valueOf(value));
			if (info != null) {
				gen.writeObjectField("label", info);
			}
			gen.writeObjectField("value", value);
			gen.writeEndObject();
		} else {
			gen.writeNull();
		}
	}
	public JsonSerializer<T> createContextual(SerializerProvider prov, BeanProperty property)
			throws JsonMappingException {
		Dict filterSerialize = (Dict) property.getAnnotation(Dict.class);
		if (filterSerialize == null) {
			throw new RuntimeException("未注解@Dict");
		} else {
			this.type = filterSerialize.type();
			return this;
		}
	}
}

字典表里的data_value和机构表里面的type数据相同
在这里插入图片描述
机构表里面的type字段数据为0
在这里插入图片描述

package xx.xx.persistence;
public interface Dict {
	String getType();
	String getName();
	String getDataValue();
}
package xx.xx.service;
import xx.xx.persistence.Dict;
import java.util.List;
public interface DictService {
	List<Dict> getAllList();
}

机构实体类中的type参数添加@Dict注解
@Dict(type=“sys_office_type”)对应字典表中的type字段数据
在这里插入图片描述
前端请求机构对象中的type字段中会出现@Dict注解中的label,value
label对应字典中的name字段,value对应字典中的data_value
在这里插入图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值