I have some jersey resource methods set with @JsonView annotation in order to filter the fields returned in the response. I\'d like to be able in some cases to override the
You can customize the Jackson object writer inside a jersey filter based on the resource method annotation using the Jackson 2.3 ObjectWriterModifier/ObjectReaderModifier feature.
Refer to the Jersey documentation how to define filters and interceptors. This question may be helpful for Jersey 1.x.
Here is an example which register an ObjectWriterModifier thread local instance that changes the view class for the JAX-RS Jackson provider. I have not test the code against a JAX-RS implementation, but I believe it should work (let me know if it doesn't).
public class JacksonObjectWriterModifier {
private static class JsonViewOverrider extends ObjectWriterModifier {
private final Class> view;
private JsonViewOverrider(Class> view) {
this.view = view;
}
@Override
public ObjectWriter modify(EndpointConfigBase> endpoint, MultivaluedMap responseHeaders,
Object valueToWrite, ObjectWriter w, JsonGenerator g) throws IOException {
return w.withView(view);
}
}
private static class View1 {
}
private static class View2 {
}
public static class Bean {
@JsonView(View1.class)
public final String field1;
@JsonView(View2.class)
public final String field2;
public Bean(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
}
public static void main(String[] args) throws IOException {
Bean b = new Bean("a", "b");
JacksonJsonProvider provider = new JacksonJsonProvider();
provider.setDefaultView(View1.class);
// commenting the following line falls back to the View1
ObjectWriterInjector.set(new JsonViewOverrider(View2.class));
provider.writeTo(b, Bean.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, System.out);
}