How to override @JsonView methods in jersey resources

I have some jersey resource methods installed with the @JsonView annotation to filter the fields returned in the response. I would like in some cases it would be possible to override the JsonView set in annotations to others or sometimes completely disable it. (some queryParams will be used to determine which view should be set up for rendering or if it should be disabled). Any ideas?

+3
source share
1 answer

You can configure the creator of the Jackson object inside the jersey filter based on the annotation of the resource method using the Jackson 2.3 function ObjectWriterModifier / ObjectReaderModifier .

, . Jersey 1.x.

, ObjectWriterModifier, JAX-RS Jackson. JAX-RS, , ( , ).

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<String, Object> 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);
    }
+2

All Articles