问题描述
我的POJO类在字段声明上有 @JsonIgnore
,而不是getter和setter方法。它是一个生成的文件,我不能改变太多。
My POJO class has @JsonIgnore
on the declaration of a field, not on the getter and setter methods. It is a generated file and I can't change much in it.
如何使用 JsonGenerator.Setting
?在getter和setter上使用 @JsonIgnore
。但是无法修改生成的POJO类。
How do I ignore that field while writing using JsonGenerator.Setting
? Using @JsonIgnore
on getters and setters works. But can't modify the generated POJO class.
推荐答案
配置Jackson只使用字段注释
在字段上放置注释后,您可以配置 ObjectMapper
以仅使用字段注释,忽略getter和setter方法的注释: / p>
Configuring Jackson to use only field annotations
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 mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Jackson混合注释
它是修改POJO时不是一个很好的选择。您可以将其视为一种面向方面的方式,在运行时添加更多注释,以增加静态定义的注释。
Jackson mix-in annotations
It's a great alternative when modifying your POJOs is not an option. 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();
}
然后配置 ObjectMapper
使用定义的接口(或类)作为POJO的混合:
Then configure ObjectMapper
to use the defined interface (or class) as a mix-in for your POJO:
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.addMixIn(Foo.class, FooMixIn.class);
以下是一些使用注意事项:
Here are some usage considerations:
- 杰克逊认可的所有注释集都可以混合使用。
- 可以混合使用各种注释(成员方法,静态方法,字段,构造函数注释)。
- 只有方法(和字段)名称和签名用于匹配注释:访问定义(
私有
,protected
,...)和方法实现被忽略。
- All annotation sets that Jackson recognizes can be mixed in.
- 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.
有关详细信息,请查看。
For more details, check this page.
这篇关于忽略一个字段而不用Jackson修改POJO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!