【问题标题】:how to fetch anotations values in writeTo method of MessageBodyWriter in jersey?如何在球衣的 MessageBodyWriter 的 writeTo 方法中获取注释值?
【发布时间】:2016-12-19 08:25:47
【问题描述】:

我正在覆盖MessageBodyWriterWriteTo 方法:

@Override
public void writeTo(Detail detail, Class<?> type, Type genericType, Annotation[] annotation, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
}

有一个annotation 参数。其实我是想从中获取view注解,这样我就可以根据view返回Detail数据。

这是我的WriteTo 代码:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
mapper.writerWithView(JSONView.CustomerView.class).writeValue(entityStream, detail);

其实我是想从注解中获取视图名,这样就可以根据视图返回具体的数据了。

如何从注解中获取view 类名?

这是我的资源代码:

@POST
@Produces({MediaType.APPLICATION_JSON})
@Path("testDetail")
@JsonView(JSONView.TicketView.class)
public TestDetail testDetail()
{
    TestDetail testDetail = new TestDetail();
    return testDetail;
}

【问题讨论】:

    标签: java rest jax-rs jersey-2.0


    【解决方案1】:

    你可以这样做:

    JsonView jsonView = this.getClass().getAnnotation(JsonView.class);
    

    JsonView jsonView = TestDetail.class.getAnnotation(JsonView.class);
    

    你使用的方法:

    Method method = this.getClass().getMethod("testDetail"); (or this.getClass().getDeclaredMethod("testDetail"))
    JsonView type = method.getAnnotation(JsonView.class);
    

    然后做:

    type.value()
    

    【讨论】:

    • 对不起,你想要的方法,我会更新代码。
    • 在哪个包方法中??
    • @PrashantSharma 这是反射,所以 java.lang.reflect.Method。你只需要检查返回类型。
    【解决方案2】:

    我知道您对在 MessageBodyWriter 的自定义实现中获取资源方法注释特别感兴趣。但是你不需要为了你在问题中提到的目的这样做

    JAX-RS 的 Jackson 模块开箱即用地提供了此功能,您无需自己编写代码。引用project page

    除了注释值类之外,还可以将 Jackson 注释的子集与提供程序一起使用。 以下是适用于所有格式的受支持注释的简短列表:

    • @JsonView 可用于定义特定端点的活动视图

    [...]

    jersey-media-json-jackson 工件依赖于 jackson-jaxrs-json-provider 工件,它为您提供了这样的功能。因此,只需将 Jackson 配置为您的 JSON 提供程序(有关更多详细信息,请参阅此 answer),并且对 @JsonView 的支持将开箱即用。

    【讨论】:

    • 你好,我想这样做。我对它有要求。 :-) 请提出一些建议
    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2014-05-25
    • 2014-02-12
    • 2020-07-27
    • 2016-04-05
    • 1970-01-01
    • 2014-03-13
    相关资源
    最近更新 更多