简体   繁体   English

忽略字段而不使用 Jackson 修改 POJO 类

[英]Ignoring a field without modifying the POJO class with Jackson

My POJO class has @JsonIgnore on the declaration of a field, not on the getter and setter methods.我的 POJO 类在字段声明上有@JsonIgnore ,而不是在 getter 和 setter 方法上。 It is a generated file and I can't change much in it.这是一个生成的文件,我不能对其进行太多更改。

How do I ignore that field while writing using JsonGenerator.Setting ?使用JsonGenerator.Setting编写时如何忽略该字段? Using @JsonIgnore on getters and setters works.在 getter 和 setter 上使用@JsonIgnore有效。 But can't modify the generated POJO class.但是不能修改生成的POJO类。

Configuring Jackson to use only field annotations配置 Jackson 以仅使用字段注释

Once the annotations are placed on the fields, you can configure ObjectMapper to use only the fields annotations, ignoring the annotations of getters and setters methods:一旦将注解放置在字段上,您就可以配置ObjectMapper以仅使用字段注解,而忽略 getter 和 setter 方法的注解:

ObjectMapper mapper = new ObjectMapper();    
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

Jackson mix-in annotations Jackson 混合注解

It's a great alternative when modifying your POJOs is not an option.当修改 POJO 不是一种选择时,这是一个很好的选择。 You can think of it as a kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.您可以将其视为一种在运行时添加更多注释的面向方面的方式,以增强静态定义的注释。

Define a mix-in annotation interface (class would do as well):定义一个混合注释接口(类也可以):

public interface FooMixIn {

    @JsonIgnore
    String getBar();
}

Then configure ObjectMapper to use the defined interface (or class) as a mix-in for your POJO:然后配置ObjectMapper以使用定义的接口(或类)作为 POJO 的混合:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
                                        .addMixIn(Foo.class, FooMixIn.class); 

Here are some usage considerations:以下是一些使用注意事项:

  • All annotation sets that Jackson recognizes can be mixed in. Jackson 识别的所有注释集都可以混入。
  • All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in.各种注解(成员方法、静态方法、字段、构造器注解)都可以混入。
  • Only method (and field) name and signature are used for matching annotations: access definitions ( private , protected , ...) and method implementations are ignored.只有方法(和字段)名称和签名用于匹配注释:访问定义( privateprotected 、...)和方法实现被忽略。

For more details, check this page .有关更多详细信息,请查看此页面

将这些字段定义为transients并避免它们被序列化,无论您使用什么 json 注释...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM