0

My Entity Object has some private fields with public getter and setter and also a private list without get or set, because i want to check the items before they get added to the list.

Looks something like this:

public class MyData{
  private String name;
  private String description;
  private List<MoreData> moreData;

  public String getName(){...}
  public String setName(){...}
  public String getDescription(){...}
  public String setDescription(){...}

  public void addMoreData(MoreData data){
    // validate Data
    moreData.add(data);
  }
}

Now i would like to serialize this Class including the list to json to send it to my frontend, but apparently private fields are ignored.

An solution would be a seperate DTO but this is a lot of boilerplate code i would like to avoid. So how can i tell my RestController / Jackson to serialize my private fields (lists)?

1 Answers1

1

For serialization you would only need to add the getter. Adding getter wouldn't interfere with your goal to validate an item before it is added to the list.

Also if you wanted you could also add a setter that looks something like this (so the items would still be validated)

public void setMoreData(List<MoreData> data){
    data.forEach(this::addMoreData);
}

Another option would be making a DTO like you said.

Janar
  • 2,623
  • 1
  • 22
  • 32