Reputation: 4483
Java 1.8, Jackson library 2.1.5
I need to override the behaviour of how an object is serialized in json.
What i need is to ignore the bonus
property from the serialized json response in case the value is null and the employee is a Partner
employee. However trying the code below does not seem to work as expected.
class Employee{
private String bonus;
public String getBonus(){return bonus;}
public String setBonus(){this.bonus = bonus;}
}
class Partner extends Employee{
@Override
@JsonInclude(NON_NULL)
public String getBonus(){return super.getBonus();}
}
Any help?
Upvotes: 4
Views: 1376
Reputation: 3959
If you can get by with excluding all null
properties, then you can use the @JsonSerialize
on the class. The following test runs successfully for me using Jackson 2.1.5:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.junit.Test;
public class SomeTest {
public static class Employee {
private String bonus;
public String getBonus() {
return bonus;
}
public void setBonus(String bonus) {
this.bonus = bonus;
}
}
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public static class Partner extends Employee {
@Override
public String getBonus() {
return super.getBonus();
}
}
@Test
public void testSerialize() throws Exception {
Employee employee = new Employee();
Partner partner = new Partner();
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("Employee: " + objectMapper.writeValueAsString(employee));
System.out.println(" Partner: " + objectMapper.writeValueAsString(partner));
}
}
Output:
Employee: {"bonus":null}
Partner: {}
Upvotes: 2