zoukankan      html  css  js  c++  java
  • Json序列化,前缀或者脱敏实现

    注解+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;

    结果

    注解+序列化的实现

  • 相关阅读:
    mysql nulls first nulls last解决方案
    解决Incorrect integer value: '' for column 'id' at row 1的方法
    Centos 7.4忘记密码的情况下,修改root密码
    解决pom文件第一行报错(unknown)-亲测有效
    快慢指针应用总结
    gRPC 小记
    [3D跑酷] DataManager
    [3D跑酷] GameManager
    发布资源到Asset Store
    真人动作捕捉系统 for Unity
  • 原文地址:https://www.cnblogs.com/xiebq/p/10139987.html
Copyright © 2011-2022 走看看