1. 字典注解更新, 可选是否重写到原先的column 上为字典对应值

This commit is contained in:
zhaowenyuan 2024-06-17 11:13:20 +08:00
parent c33e45a4aa
commit a2fc42bfdf
2 changed files with 16 additions and 3 deletions

View File

@ -19,4 +19,9 @@ public @interface DictFormat {
* 设置字典的type值 (: sys_user_sex)
*/
String dictType() default "";
/**
* 是否重写覆盖本身key
*/
boolean rewrite() default false;
}

View File

@ -21,12 +21,14 @@ import java.util.Objects;
public class DictJsonSerializer extends JsonSerializer<Object> implements ContextualSerializer {
private String dictType;
private boolean rewrite;
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
DictFormat anno = property.getAnnotation(DictFormat.class);
if (Objects.nonNull(anno) && StrUtil.isNotBlank(anno.dictType())) {
this.dictType = anno.dictType();
this.rewrite = anno.rewrite();
return this;
}
return prov.findValueSerializer(property.getType(), property);
@ -34,10 +36,16 @@ public class DictJsonSerializer extends JsonSerializer<Object> implements Contex
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
try {
String dictLabel = DictUtils.getDictLabel(dictType, Convert.toStr(value));
if (rewrite) {
// 重写了 原先的 code
gen.writeString(dictLabel);
}else {
// value == code
gen.writeObject(value);
gen.writeFieldName(gen.getOutputContext().getCurrentName() + "Name");
String dictLabel = DictUtils.getDictLabel(dictType, Convert.toStr(value));
gen.writeString(dictLabel);
}
} catch (BeansException e) {
log.error("字典数据未查到, 采用默认处理【{}】", e.getMessage());
gen.writeObject(value);