2015-04-17 84 views
2

我使用Jersey 1.19来实现休息api和Jackson提供JSON支持。我的资源实体是深深嵌套的,我希望在发送它们之前将它们展平。我也想提供对基于查询参数的过滤的支持。示例GET /users/1234返回整个用户资源,而GET /users/1234?filter=username,email将仅返回包含给定字段的用户资源。Jersey 1.x与Jackson:定制响应JSON

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

任何想法,欢迎

回答

1

所以我很困惑如何访问这些PARAMS这个方法。

您可以将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 S代表不同的方案。您也可以将UriInfo注入ContextResolverFor example

+0

谢谢。注入UriInfo是我需要的! – iTwenty

0

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

的Try ...

@Context 
UriInfo uriInfo; 
@Context 
HttpServletRequest request; 

,或者尝试改变你的休息方法,像...

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