gpt4 book ai didi

java - 如何在 Jersey 中的MessageBodyWriter的writeTo方法中获取注释值?

转载 作者:行者123 更新时间:2023-12-03 03:29:53 26 4
gpt4 key购买 nike

我正在重写 MessageBodyWriterWriteTo 方法:

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

有一个注释参数。实际上我想从中获取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 名称,以便我可以根据 View 返回特定数据。

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

这是我的资源代码:

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

最佳答案

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

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

In addition to annotation value classes, it is also possible to use a subset of Jackson annotations with provider. Here is a short list of supported annotations that work with all formats:

  • @JsonView can be used to define active view for specific endpoint

[...]

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

关于java - 如何在 Jersey 中的MessageBodyWriter的writeTo方法中获取注释值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com