赞
踩
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import demo.func.SensitiveJsonSerializer; import demo.func.SensitiveStrategy; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义jackson注解,标注在属性上 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @JacksonAnnotationsInside @JsonSerialize(using = SensitiveJsonSerializer.class) public @interface Sensitive { //脱敏策略 SensitiveStrategy strategy(); }
import java.util.function.Function; public enum SensitiveStrategy { /** * 手机号 */ PHONE(s -> s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")); private final Function<String, String> desensitizer; SensitiveStrategy(Function<String, String> desensitizer) { this.desensitizer = desensitizer; } public Function<String, String> desensitizer() { return desensitizer; } }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import demo.annotation.Sensitive; import java.io.IOException; import java.util.Objects; /** * 序列化注解自定义实现 * JsonSerializer<String>:指定String 类型,serialize()方法用于将修改后的数据载入 */ public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer { private SensitiveStrategy strategy; @Override public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException { Sensitive annotation = property.getAnnotation(Sensitive.class); if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) { this.strategy = annotation.strategy(); return this; } return provider.findValueSerializer(property.getType(), property); } @Override public void serialize(String value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeString(strategy.desensitizer().apply(value)); } }
@Data
@AllArgsConstructor
public class SecretStr {
@Sensitive(strategy = SensitiveStrategy.PHONE)
private String phone;
private String name;
}
@RestController
public class TestController {
@GetMapping("/getSecret")
public R<SecretStr> getSecret(){
SecretStr secretStr = new SecretStr("15068433245","zs");
return R.success(secretStr);
}
}
{
"code": 200,
"msg": "操作成功",
"data": {
"phone": "150****3245",
"name": "zs"
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。