使用条件动态排除Jackson json序列化中的POJO属性 [英] Using conditions to dynamically exclude POJO property in Jackson json serialization
问题描述
我需要动态排除定义的POJO的List中的某些属性。
要序列化的主要POJO是:
I have a requirement to dynamically exclude certain property within a List of a defined POJO. The main POJO to be serialized is:
public class Foo
{
List<Bar> bar;
public void setBar(List<Bar> bar)
{
this.bar = bar;
}
public List<Bar> getBar()
{
return this.bar;
}
public static class Bar
{
private int id;
private boolean ignoreId;
private String name;
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return this.id;
}
public void setIgnoreId(boolean ignoreId)
{
this.ignoreId = ignoreId;
}
public boolean isIgnoreId()
{
return this.ignoreId;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
}
}
id如果要忽略ignoreId = true,如下所示:
id is to be ignored if ignoreId = true, like so:
[
{ "id": "1", "name": "one" },
{ "name": "two" }
{ "name": "three" }
{ "id": "4", "name": "four" }
]
目前,我尝试过使用 JsonFilter
和 JacksonJsonViews
但无法获得所需的输出。
如果有任何指针可用于达到此目的,我会很高兴。
At the moment, I have tried using JsonFilter
and JacksonJsonViews
but couldn't get the required output.
I would be glad if any pointer can be given towards achieving this.
推荐答案
你应该写一个自定义杰克逊过滤器,它会根据其他属性值过滤掉POJO属性。您应该覆盖 PropertyFilter.serializeAsField()
方法以访问序列化对象的实例。以下是一个示例:
You should write a custom Jackson filter which would filter out a POJO property depending on other property value. You should override the PropertyFilter.serializeAsField()
method to get access to the instance of the serialized object. Here is an example:
public class JacksonFilter2 {
@JsonFilter("filter")
public static class Bar {
public final int id;
@JsonIgnore
public final boolean ignoreId;
public final String name;
public Bar(int id, boolean ignoreId, String name) {
this.id = id;
this.ignoreId = ignoreId;
this.name = name;
}
}
public static class ExcludeIdFilter extends SimpleBeanPropertyFilter {
@Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
@Override
protected boolean include(PropertyWriter writer) {
return true;
}
@Override
public void serializeAsField(Object pojo,
JsonGenerator jgen,
SerializerProvider provider,
PropertyWriter writer) throws Exception {
if (pojo instanceof Bar
&& "id".equals(writer.getName())
&& ((Bar) pojo).ignoreId) {
writer.serializeAsOmittedField(pojo, jgen, provider);
} else {
super.serializeAsField(pojo, jgen, provider, writer);
}
}
}
public static void main(String[] args) throws JsonProcessingException {
List<Bar> bars = Arrays.asList(new Bar(1, false, "one"), new Bar(2, true, "two"));
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(new SimpleFilterProvider().addFilter("filter", new ExcludeIdFilter()));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bars));
}
}
输出:
[ {
"id" : 1,
"name" : "one"
}, {
"name" : "two"
} ]
这篇关于使用条件动态排除Jackson json序列化中的POJO属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!