gpt4 book ai didi

java - Jersey 1.x 与 jackson : Customising the response JSON

转载 作者:行者123 更新时间:2023-11-30 11:05:18 25 4
gpt4 key购买 nike

我正在使用 Jersey 1.19 来实现 rest api,并使用 Jackson 来提供 JSON 支持。我的资源实体嵌套很深,我想在发送它们之前将它们展平。我还想提供对基于查询参数的过滤的支持。示例 GET/users/1234 返回整个用户资源,而 GET/users/1234?filter=username,email 将返回仅包含给定字段的用户资源。

我目前采用的方法是 JsonSerializer 的子类,它使层次结构扁平化,但无法处理基于参数的过滤,因为它独立于请求/响应周期。 Google 搜索将我指向 MessageBodyWriter。看起来像我需要的,但是 writeTo method处理序列化的方法不采用任何可以让我访问请求的参数,因此也不需要访问查询参数。所以我很困惑如何在这个方法中访问这些参数。

欢迎任何想法

最佳答案

So I am confused how to access those params in this method.

你可以注入(inject)UriInfo使用 @Context 进入 MessageBodyWriter。然后调用 uriInfo.getQueryParameter() 获取参数。例如

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class YourWriter implements MessageBodyWriter<Something> {

@Context UriInfo uriInfo;

...
@Override
public void writeTo(Something t, Class<?> type, Type type1, Annotation[] antns,
MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out)
throws IOException, WebApplicationException {

String filter = uriInfo.getQueryParameters().getFirst("filter");
}
}

另一种选择是使用 ContextResolver 并针对不同的场景使用预配置的 ObjectMapper。您还可以将 UriInfo 注入(inject)到 ContextResolver 中。 For example

关于java - Jersey 1.x 与 jackson : Customising the response JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700677/

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