2015-04-17 80 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) ... 
...