我正在尝试使用不同的JsonFilters来序列化同一类的对象。
想象一下Foo课程
public class Foo{
Bar p1;
Bar p2;
}
和班级栏
@JsonFilter("myFilter")
public class Bar{
String prop1;
String prop2;
String prop3;
}
现在我想要实现的是为Foo类中的变量p1和p2设置不同的JsonFilters。
例如。对于p1我想序列化只有prop1,对于p2我想序列化prop2和prop3。 获得以下json
{
"p1": { "prop1":"blabla" }
"p2": { "prop2":"blabla", "prop3":"blabla" }
}
所以我会使用以下过滤器,以便只有“prop1”会被序列化:
FilterProvider filter = new SimpleFilterProvider().addFilter("myFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("prop1"));
String json = new ObjectMapper().filteredWriter(filter).writeValueAsString(foo)
但是使用它也会导致p2只被序列化为prop1
我想为p2创建另一个过滤器,如下所示:
FilterProvider filter2 = new SimpleFilterProvider().addFilter("myFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("prop2","prop3"));
但我真的找不到如何实现它,以便p1和p2有不同的过滤器,看它们属于同一类Foo。
感谢您的阅读,希望有人能帮忙!
答案 0 :(得分:3)
从Jackson 2.3开始,@JsonFilter
注释可以放在字段和方法上。我认为它应该对你的情况有所帮助。这是一个例子:
public class JacksonFilters {
static class Bar {
final public String prop1;
final public String prop2;
final public String prop3;
Bar(final String prop1, final String prop2, final String prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
}
}
static class Foo {
@JsonFilter("myFilter1")
final public Bar p1;
@JsonFilter("myFilter2")
final public Bar p2;
Foo(final Bar p1, final Bar p2) {
this.p1 = p1;
this.p2 = p2;
}
}
public static void main(String[] args) throws JsonProcessingException {
final SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("myFilter1",
SimpleBeanPropertyFilter.filterOutAllExcept("prop1"));
filterProvider.addFilter("myFilter2",
SimpleBeanPropertyFilter.serializeAllExcept("prop2"));
final Foo bar = new Foo(new Bar("a", "b", "c"), new Bar("d", "e", "f"));
final ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(filterProvider);
System.out.println(mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(bar));
}
}
输出:
{
"p1" : {
"prop1" : "a"
},
"p2" : {
"prop1" : "d",
"prop3" : "f"
}
}