[英]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类。
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);
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:以下是一些使用注意事项:
private
, protected
, ...) and method implementations are ignored.private
、 protected
、...)和方法实现被忽略。将这些字段定义为transients
并避免它们被序列化,无论您使用什么 json 注释...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.