@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = DesensitizationJsonSerializer.class )
public @interface Desensitization {
Class<? extends AbstractDesensitization> value();
}
public class DesensitizationJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
private AbstractDesensitization desensitization;
public DesensitizationJsonSerializer(AbstractDesensitization desensitization) {
this.desensitization = desensitization;
}
public DesensitizationJsonSerializer() {
}
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(desensitization.serialize(s));;
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
JsonSerializer<?> jsonSerializer = null;
if(null == beanProperty) jsonSerializer = serializerProvider.findNullValueSerializer(beanProperty);
if(!Objects.equals(beanProperty.getType().getRawClass(), String.class))
jsonSerializer = serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
if(Objects.equals(beanProperty.getType().getRawClass(), String.class)){
jsonSerializer = setDesensitization(jsonSerializer, beanProperty);
}
return jsonSerializer;
}
/**
* 设置脱敏
* @param beanProperty
* @return
*/
private JsonSerializer<?> setDesensitization(JsonSerializer<?> jsonSerializer, BeanProperty beanProperty) {
Desensitization desensitization = beanProperty.getAnnotation(Desensitization.class);
if (desensitization == null) desensitization = beanProperty.getContextAnnotation(Desensitization.class);
if (desensitization != null) {
//设置脱敏实例
try {
jsonSerializer = new DesensitizationJsonSerializer(desensitization.value().newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return jsonSerializer;
}
}
public abstract class AbstractDesensitization {
/**
* 脱敏
* @param value
* @return
*/
public abstract String serialize(String value);
}
示例:
public class IdCardDesensitization extends AbstractDesensitization {
@Override
public String serialize(String value) {
return value.replaceAll("(?<=\\w{3})\\w(?=\\w{4})","*");
}
}
public class PhoneDesensitization extends AbstractDesensitization{
@Override
public String serialize(String value) {
return value.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
}
}
使用,在返回实体中加上
/**
* 手机号
*/
@Desensitization(PhoneDesensitization.class)
private String phoneNumber;
/**
* 身份证
*/
@Desensitization(IdCardDesensitization.class)
private String idCard;
效果
{
"phoneNumber": "154****3333",
"idCard": "332***********3423"}