且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Jackson 进行动态序列化 - 删除带有特定注释的字段

更新时间:2023-01-16 08:32:38

不清楚是要静态还是动态忽略给定的属性.无论如何,看起来你已经过度设计了.

It's not clear whether you want to ignore a given property statically or dynamically. Anyways, looks like you have over-engineered it.

首先,我想确保您遇到了 @JsonIgnore 之前.如果它不适合您的需求,您可以定义您的自定义忽略注释如下:

First of all, I want to make sure that you came across @JsonIgnore before. If it doesn't suit your needs, you could define your custom ignore annotation as following:

@Retention(RetentionPolicy.RUNTIME)
public @interface Hidden {

}

然后选择最适合您需求的方法:

Then pick the approach that best suit your needs:

扩展JacksonAnnotationIntrospector 并覆盖检查忽略标记的方法:

Extend JacksonAnnotationIntrospector and override the method that checks for the ignore marker:

public class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {

    @Override
    public boolean hasIgnoreMarker(AnnotatedMember m) {
        return super.hasIgnoreMarker(m) || m.hasAnnotation(Hidden.class);
    }
}

配置ObjectMapper 使用您的注释内省器:

Configure ObjectMapper to use your annotation introspector:

ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new CustomAnnotationIntrospector());

注解内省每个类仅发生一次,因此您无法动态更改您使用的标准(如果有).在这个答案中可以看到一个类似的例子.

The annotation introspection occurs only once per class so you can not dynamically change the criteria you use (if any). A similar example can be seen in this answer.

扩展BeanSerializerModifier 修改将被序列化的属性:

Extend BeanSerializerModifier to modify the properties that will be serialized:

public class CustomBeanSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, 
            BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {

        return beanProperties.stream()
                .filter(property -> property.getAnnotation(Hidden.class) == null)
                .collect(Collectors.toList());
    }
}

然后将其添加到 Module 并将其注册到您的 ObjectMapper:

Then add it to a Module and register it to your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new SimpleModule() {

    @Override
    public void setupModule(SetupContext context) {
        super.setupModule(context);
        context.addBeanSerializerModifier(new CustomBeanSerializerModifier());
    }
});

这种方法允许您动态忽略属性.

This approach allows you to ignore properties dynamically.