You can consider using the Jackson Json views. Basically, you replace the @JsonIgnore
annotation on the Jackson view annotation with a view type and enable it depending on the context. Here is an example for a plain object mapper:
public class JacksonView {
public static interface View1 {
}
public static interface View2 {
}
public static class Bean {
@JsonView(View1.class)
public final String field1;
@JsonView(View2.class)
public final String field2;
public final String field3;
public Bean(String field1, String field2, String field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
}
public static void main(String[] args) throws JsonProcessingException {
Bean bean = new Bean("a", "b", "c");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper
.writer()
.withView(View2.class)
.writeValueAsString(bean));
}
}
Output:
{"field2":"b","field3":"c"}
To make it work in JAX-RS you should enable the specific view by annotating your HTTP method resources as described here. Example:
@GET
@JsonView(View1.class)
public Bean doGet() {...}
@POST
@JsonView(View2.class)
public void doPost(Bean bean) {...}