Java 1.8,Jackson library 2.1.5
我需要覆盖json中对象序列化的行为。
我需要的是忽略序列化json响应中的bonus
属性,以防值为null且雇员是Partner
员工。但是,尝试下面的代码似乎没有按预期工作。
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();}
}
任何帮助?
答案 0 :(得分:2)
如果您可以排除所有null
属性,那么您可以在课程中使用@JsonSerialize
。以下测试使用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));
}
}
<强>输出:强>
Employee: {"bonus":null}
Partner: {}