@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