注解结合继承JsonSerialize实现ContextualSerializer,通过注解显式的声明序列化方式,实现返回的对象进行转译。
代码示例:
1、自定义注解
/**
* @Author hmh
* @Description 嵌入式转译注解,生效点:request请求完成返回时,进行序列化过滤,并嵌入实现
* @Description 失效点: service业务处理层是不会生效的,序列化对象转Json,或者其他格式对象后,也是无法过滤到的
**/
@JacksonAnnotationsInside
@JsonSerialize(using = DicTransContextualSerializer.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EmbedTrans {
/**
* dic类型
*
* @return
*/
@NotBlank
String dictType();
/**
* 转译输出字段
*
* @return
*/
String fieldName() default "";
/**
* 需要调用查询字典的方法
*
* @return
*/
DicTypeEnum dicMetohd() default DicTypeEnum.NORMAL_CODE_TRANS_NAME;
}
2,实现ContextualSerializer获取回调
public class DicTransContextualSerializer extends JsonSerializer<String> implements ContextualSerializer {
private String dictType;
private String fieldName;
private DicTypeEnum dicTypeEnum;
public DicTransIntegerSerializer(String dictType, String fieldName, DicTypeEnum dicTypeEnum) {
this.dictType = dictType;
this.fieldName = fieldName;
this.dicTypeEnum = dicTypeEnum;
}
public DicTransIntegerSerializer() {
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
if (beanProperty != null) {
if (Objects.equals(beanProperty.getType().getRawClass(), int.class)
|| Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
EmbedTrans t = beanProperty.getAnnotation(EmbedTrans.class);
if (t != null) {
String beanFieldName = beanProperty.getName();
if (StringUtils.hasText(t.fieldName())) {
beanFieldName = t.fieldName();
}
DicTypeEnum dicTypeEnum = DicTypeEnum.NORMAL_CODE_TRANS_NAME;
if (t.dicMetohd() != null) {
dicTypeEnum = t.dicMetohd();
}
if (Objects.equals(beanProperty.getType().getRawClass(), int.class)) {
return new DicTransIntegerSerializer(t.dictType(), beanFieldName + "Text", dicTypeEnum);
} else {
return new DicTransStringSerializer(t.dictType(), beanFieldName + "Text", dicTypeEnum);
}
}
}
return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
}
return serializerProvider.findNullValueSerializer(beanProperty);
}
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeObject(integer);
jsonGenerator.writeFieldName(fieldName);
String val = String.valueOf(integer);
String getval = DicUtil.getval(dicTypeEnum, dictType, val);
jsonGenerator.writeString(getval);
}
博主原文:自定义注解结合继承JsonSerialize实现ContextualSerializer,实现返回结果转译-CSDN博客