0

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"]
}
Alex Man
  • 4,746
  • 17
  • 93
  • 178
  • In addition to answer below, try and think about encapsulation when designing classes - you don't want to make member variables `public`, make them 'private` (or `protected` if you implement my subclassing suggestion) - you want to protect your classes from having their state changed improperly by other classes. – NickJ Oct 18 '15 at 09:46

1 Answers1

2

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;
}
Community
  • 1
  • 1
NickJ
  • 9,380
  • 9
  • 51
  • 74
  • do you have any suggestion for this http://stackoverflow.com/questions/33198270/common-dto-for-two-incoming-rest-json – Alex Man Oct 18 '15 at 13:43