How to override @JsonView in jersey resource metho

2019-02-25 08:15发布

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 JsonView set in the annotation with another one or sometimes completely disable it. (some queryParam would be used to define which view should set for rendering or if it should be disabled). Any ideas?

1条回答
Animai°情兽
2楼-- · 2019-02-25 08:42

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<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);
    }
查看更多
登录 后发表回答