You can achieve this with @JsonView
(kudos to baeldung):
@JsonView
indicates the View in which the property will be included for serialization/deserialization.
For example, we'll use @JsonView to serialize an instance of Item entity.
First, let's start with the views:
public class Views {
public static class Public {}
public static class Internal extends Public {}
}
Next here's the Item entity using the views:
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
}
Finally, the full test:
@Test
public void whenSerializingUsingJsonView_thenCorrect()
throws JsonProcessingException {
Item item = new Item(2, "book", "John");
String result = new ObjectMapper()
.writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("2"));
assertThat(result, not(containsString("John")));
}