How to override @JsonView in jersey resource methods

╄→гoц情女王★ 提交于 2019-12-01 19:10:13
Alexey Gavrilov

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);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!