Alex Man
Alex Man

Reputation: 4886

how to ignore json attribute dynamically

Let say I am having a Common Employee dto like as shown below

public class Employee {

    @JsonProperty("name")
    public String name;

    @JsonProperty("departments")
    public List<Department> departments;

    @JsonProperty("designation")
    public String designation;

    //setters and getters
}

The Employee dto can be used for both Staffs and Managers. I am consuming an external REST service from where I will get the Staffs and Managers details. For Staffs the incoming json won't contains the field departments, but for Managers the incoming json will contain an additional department field. Staffs and Managers incoming json are as shown below

Staff json

{
  "name": "Vineeth",
  "designation": "Developer"
}

Manager json

{
  "name": "Rohit",
  "designation": "Manager",
  "departments": ["Dept1", "Dept2", "Dept3"]
}

The unmarshalling is working fine but the problem is when I marshal again back to json for Staffs I am getting like this

{
  "name": "Vineeth",
  "designation": "Developer",
  "departments": null
}

Can anyone please tell me how to ignore or remove fields if the field is not present during marshaling dto like

For Staffs it should be like as shown below after marshaling

{
  "name": "Vineeth",
  "designation": "Developer"
}

and for Managers its should be like as shown below after marshaling

{
  "name": "Rohit",
  "designation": "Manager",
  "departments": ["Dept1", "Dept2", "Dept3"]
}

Upvotes: 0

Views: 884

Answers (1)

NickJ
NickJ

Reputation: 9559

If Employees always have department of null, then perhaps it is acceptable to jell the JSON marshaller to ignore nulls. This can be achieved using an annotation as descriped here :How to tell Jackson to ignore a field during serialization if its value is null?

Alternatively, you might consider making Employee an abstract class, removing the departments list from it, subclassing it with Staff and Manager.

The 'Manager' class would be abstract and define name and designation:

public abstract class Manager {

  @JsonProperty("name")
  public String name;

  @JsonProperty("designation")
  public String designation;
}

The 'Staff` class would be very simple:

public class Staff extends Employee {}

The 'Manager' class would contain the Departments list:

public class Manager extends Employee {
  @JsonProperty("departments")
  public List<Department> departments;
}

Upvotes: 2

Related Questions