如何在Jackson ObectMapper中进行序列化时添加@JsonIgnore带注释的字段 [英] How to add @JsonIgnore annotated fields in serializing in Jackson ObectMapper
问题描述
在通过Jackson ObjectMapper
序列化对象时,我需要添加带@JsonIgnore
注释的字段.我知道您可以为我提供从类中删除@JsonIgnore
批注的方法,但是我需要它们在我的应用程序的某些部分可忽略.在我的应用程序的另一部分中,我需要在我的json
字符串中包含那些带有@JsonIgnore
注释的字段.
I need to add @JsonIgnore
annotated fields while serializing an object by Jackson ObjectMapper
. I know you may offer me to remove the @JsonIgnore
annotation from my class, but I need they are ignorable in some part of my application. And in another part of my application I need to have those @JsonIgnore
annotated fields in my json
string.
推荐答案
您可以定义SimpleBeanPropertyFilter和FilterProvider.
You can define a SimpleBeanPropertyFilter and FilterProvider.
首先使用此类自定义过滤器为您的课程添加注释:
First annotate your class with custom filter like this:
@JsonFilter("firstFilter")
public class MyDtoWithFilter {
private String name;
private String anotherName;
private SecondDtoWithFilter dtoWith;
// get set ....
}
@JsonFilter("secondFilter")
public class SecondDtoWithFilter{
private long id;
private String secondName;
}
这就是您将动态序列化对象的方式.
and this is how you will dynamically serialise your object.
ObjectMapper mapper = new ObjectMapper();
// Field that not to be serialised.
SimpleBeanPropertyFilter firstFilter = SimpleBeanPropertyFilter.serializeAllExcept("anotherName");
SimpleBeanPropertyFilter secondFilter = SimpleBeanPropertyFilter.serializeAllExcept("secondName");
FilterProvider filters = new SimpleFilterProvider().addFilter("firstFilter", firstFilter).addFilter("secondFilter", secondFilter);
MyDtoWithFilter dtoObject = new MyDtoWithFilter();
String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
这篇关于如何在Jackson ObectMapper中进行序列化时添加@JsonIgnore带注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!