假设我有一个普通员工,如下所示
public class Employee {
@JsonProperty("name")
public String name;
@JsonProperty("departments")
public List<Department> departments;
@JsonProperty("designation")
public String designation;
//setters and getters
}
员工dto可用于员工和经理。我正在使用外部REST服务,我将获得员工和经理的详细信息。对于员工来说,传入的json不会包含现场部门,但对于Managers,传入的json将包含一个额外的部门字段。来自json的员工和经理如下所示
员工json
{
"name": "Vineeth",
"designation": "Developer"
}
经理json
{
"name": "Rohit",
"designation": "Manager",
"departments": ["Dept1", "Dept2", "Dept3"]
}
解组工作正常但问题是当我再次回到json工作人员时我会这样做
{
"name": "Vineeth",
"designation": "Developer",
"departments": null
}
任何人都可以告诉我如何忽视或删除字段如果在编组过程中不存在字段,请
对于员工来说,编组后应该如下所示
{
"name": "Vineeth",
"designation": "Developer"
}
并且对于Managers来说,它应该在编组之后如下所示
{
"name": "Rohit",
"designation": "Manager",
"departments": ["Dept1", "Dept2", "Dept3"]
}
答案 0 :(得分:2)
如果员工总是拥有null
的部门,那么也许可以接受JSON marshaller来忽略空值。这可以使用此处描述的注释来实现:How to tell Jackson to ignore a field during serialization if its value is null?
或者,您可以考虑将Employee设为抽象类,从中删除部门列表,使用Staff
和Manager
对其进行子类化。
'Manager'类是抽象的,定义名称和名称:
public abstract class Manager {
@JsonProperty("name")
public String name;
@JsonProperty("designation")
public String designation;
}
'Staff`课程非常简单:
public class Staff extends Employee {}
'Manager'类将包含Departments列表:
public class Manager extends Employee {
@JsonProperty("departments")
public List<Department> departments;
}