如何在jersey资源方法中覆盖@JsonView [英] How to override @JsonView in jersey resource methods

查看:108
本文介绍了如何在jersey资源方法中覆盖@JsonView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用@JsonView注释设置的球衣资源方法,以便过滤响应中返回的字段。
我希望在某些情况下能够用另一个覆盖注释中的JsonView集,或者有时完全禁用它。
(某些queryParam将用于定义应为渲染设置的视图或是否应禁用它)。
任何想法?

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?

推荐答案

您可以使用资源方法注释在球衣过滤器内自定义Jackson对象编写器 Jackson 2.3 ObjectWriterModifier / ObjectReaderModifier功能

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.

参考 Jersey文档如何定义过滤器和拦截器。 这个问题可能是对Jersey 1.x有帮助。

Refer to the Jersey documentation how to define filters and interceptors. This question may be helpful for Jersey 1.x.

这是一个注册ObjectWriterModifier线程本地实例的示例,该实例更改了JAX-RS Jackson提供程序的视图类。我没有针对JAX-RS实现测试代码,但我相信它应该可以工作(如果没有,请告诉我)。

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);
    }

这篇关于如何在jersey资源方法中覆盖@JsonView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆