一、返回值脱敏
1、准备返回值对象
2、准备接口
3、准备脱敏注解
4、准备序列化处理类
public class SensitiveInfoSerialize extends JsonSerializer<String> implements ContextualSerializer {
private DesensitizationType type;
public SensitiveInfoSerialize() {
}
public SensitiveInfoSerialize(final DesensitizationType type) {
this.type = type;
}
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
switch (this.type) {
case ID_CARD:
value = DesensitizedUtil.idCardNum(value, 4, 2);
break;
case MOBILE_PHONE: {
value = DesensitizedUtil.mobilePhone(value);
break;
}
default:
break;
}
gen.writeString(value);
}
/**
* 序列化时获取字段注解属性
* @param serializerProvider
* @param property
* @return
* @throws JsonMappingException
*/
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
if (property != null) {
// 此demo只处理String类型字段
if (Objects.equals(property.getType().getRawClass(), String.class)) {
SensitiveInfo sensitiveInfo = property.getAnnotation(SensitiveInfo.class);
if (sensitiveInfo == null) {
sensitiveInfo = property.getContextAnnotation(SensitiveInfo.class);
}
if (sensitiveInfo != null) {
return new SensitiveInfoSerialize(sensitiveInfo.value());
}
}
return serializerProvider.findValueSerializer(property.getType(), property);
}
return serializerProvider.findNullValueSerializer(null);
}
}
实现ContextualSerializer接口后重写的JsonSerializer方法就是为了找到需要处理的属性,而集成JsonSerializer后重写的serialize方法就是为了处理需要处理的属性。
DesensitizedUtil是糊涂的工具。
就这样就可以了。
5、演示原本效果
6、增加注解后效果
在开发时返回值里的时间一定不只是Date、LocalDateTime、LocalDate,有时候也可能是字符串格式。此时常用的@JsonFormat注解就失去用武之地了,使用上面的方式也可以处理这种情况,下面进行展示。
1、返回值增加时间字段
2、原有效果
3、使用常用的@JsonFormat注解进行处理
处理字符串的时间以外,其他的时间都能正常处理,下面通过序列化的方式进行处理该字段。
4、增加字符串日期格式处理注解
5、准备序列化处理类
public class StringToDateSerialize extends JsonSerializer<String> implements ContextualSerializer {
private String sourceFormat;
private String targetFormat;
public StringToDateSerialize() {
}
public StringToDateSerialize(final String sourceFormat, final String targetFormat) {
this.sourceFormat = sourceFormat;
this.targetFormat = targetFormat;
}
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(DateUtil.format(DateUtil.parse(value,sourceFormat), targetFormat));
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
if (property != null) {
if (Objects.equals(property.getType().getRawClass(), String.class)) {
StringToDate stringToDate = property.getAnnotation(StringToDate.class);
if (stringToDate == null) {
stringToDate = property.getContextAnnotation(StringToDate.class);
}
if (stringToDate != null) {
return new StringToDateSerialize(stringToDate.source(),stringToDate.target());
}
}
return serializerProvider.findValueSerializer(property.getType(), property);
}
return serializerProvider.findNullValueSerializer(null);
}
}
6、测试效果