注解+aop
一:定義一個注解
二:在序列化時候,判斷字段上是否有注解,進行序列化的操作
三:在對應的字段上添加上注解
@Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonSerialize(using = SensitiveWordSerializer.class) public @interface SensitiveWord { SensitiveWordType sensitiveWordType() default SensitiveWordType.MOBILE ; }
public class SensitiveWordSerializer extends JsonSerializer<String> implements ContextualSerializer { private SensitiveWordType sensitiveWordType ; @Override public JsonSerializer<?> createContextual(SerializerProvider prov,BeanProperty property) throws JsonMappingException { SensitiveWord sensitiveWord = property.getAnnotation(SensitiveWord.class); if (sensitiveWord != null) { sensitiveWordType = sensitiveWord.sensitiveWordType(); } return this ; } @Override public void serialize(String value,JsonGenerator gen,SerializerProvider serializers) throws IOException, JsonProcessingException { if (!StringUtils.hasText(value)) { gen.writeString(value); return; } if (sensitiveWordType != null) { value = value.replaceAll(sensitiveWordType.getRegex() , sensitiveWordType.getReplacement()); } gen.writeString(value); } }
@SensitiveWord @ApiModelProperty(value = "機構聯系方式", example = "13688888888") private String contact;
結果
注解+序列化的實現