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 is to be ignored if ignoreId = true, like so:
[
{ "id": "1", "name": "one" },
{ "name": "two" }
{ "name": "three" }
{ "id": "4", "name": "four" }
]
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.
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:Output:
I am using Jackson 2.4.2.
Model object is:
Myy serializer is like so:
NOTE: The model class is passed through the network in a client-server architecture env
I just saw the culprit. Thanks a lot @Alexey for staying with me on this. After much try, I discover Jackson 2.4.2 might have required that I place my serialzer within the model it would work with. I wonder why though, but probably due to Java object serialization requirements, Jackson was failing to map the Filter at runtime. I hope Tatu would note this in Jackson documentation