Jackson序列化为字符串时对指定字段脱敏

枚举脱敏字段类型及规则

import java.util.function.Function;

public enum TextMaskStrategy {

    ID_NO("身份证", 18, text -> "*".repeat(text.length() - 4) + text.substring(text.length() - 4)),

    PHONE("手机号", 11, text -> text.substring(0, 3) + "*".repeat(text.length() - 7) + text.substring(text.length() - 4)),

    BANK_CARD_NO("银行卡号", 10, text -> "*".repeat(text.length() - 8) + text.substring(text.length() - 4)),

    ADDRESS("地址", 8, text -> text.substring(0, 5) + "*".repeat(text.length() - 8) + text.substring(text.length() - 3)),

    CAR_NO("车牌号", 6, text -> text.substring(0, 2) + "*".repeat(text.length() - 3) + text.substring(text.length() - 1));

    private final String textType;

    private final int minLength;
    private final Function<String, String> maskFunction;

    TextMaskStrategy(String textType, int minLength, Function<String, String> maskFunction) {
        this.textType = textType;
        this.minLength = minLength;
        this.maskFunction = maskFunction;
    }

    public String getTextType() {
        return textType;
    }

    public int getMinLength() {
        return minLength;
    }

    public Function<String, String> getMaskFunction() {
        return maskFunction;
    }
}

注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = TextMaskJsonSerializer.class)
public @interface TextMask {

    TextMaskStrategy strategy();

}

序列化器

public class TextMaskJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private TextMaskStrategy strategy;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null && value.length() >= strategy.getMinLength()) {
            gen.writeString(strategy.getMaskFunction().apply(value));
        } else {
            gen.writeString(value);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        TextMask annotation = property.getAnnotation(TextMask.class);
        if (Objects.nonNull(annotation)
                && Objects.equals(String.class, property.getType().getRawClass())) {
            this.strategy = annotation.strategy();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}

使用

在需在脱敏的字段上加上注解并指定脱敏策略

    @TextMask(strategy = TextMaskStrategy.BANK_CARD_NO)
    private String bankCardNo;
posted @   漠孤烟  阅读(99)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示