【问题标题】:Jersey 1.x with Jackson : Customising the response JSONJersey 1.x with Jackson:自定义响应 JSON
【发布时间】:2015-06-24 09:24:21
【问题描述】:

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

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

欢迎提出意见

【问题讨论】:

    标签: java json rest jersey jackson


    【解决方案1】:

    所以我很困惑如何在这个方法中访问这些参数。

    您可以将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 并针对不同的场景使用预配置的ObjectMappers。您还可以将UriInfo 注入ContextResolverFor example

    【讨论】:

    • 谢谢。我需要注入 UriInfo!
    【解决方案2】:

    如果你想走那条路,你应该能够传入一个列表和/或你可以公开 Request 对象。

    试试...

    @Context
    UriInfo uriInfo;
    @Context
    HttpServletRequest request;
    

    或尝试将您的 Rest 方法更改为...

    @GET
    @Path("/myMethodLocator")
    @Consumes(MediaType.APPLICATION_JSON)
    ...
    public <whatever type you are returning> myMethod(List<String> filterByList) ...
    ...
    

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 2011-08-13
      • 2013-07-26
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      相关资源
      最近更新 更多