iTwenty
iTwenty

Reputation: 973

Jersey 1.x with Jackson : Customising the response JSON

I am using Jersey 1.19 to implement a rest api and Jackson to provide JSON support. My resource entities are deeply nested and I want to flatten them out before sending them over. I also want to provide support for filtering based on query params. Example GET /users/1234 returns the whole user resource while GET /users/1234?filter=username,email will return the user resource with only the given fields included.

The approach I have currently taken is a subclass of JsonSerializer which flattens the hierarchy, but cannot handle parameter based filtering as it is independent of the request/response cycle. Google search pointed me to MessageBodyWriter. Looks like what I need but the writeTo method which handles the serializing doesn't take any parameter that would let me access the request, and hence the query params. So I am confused how to access those params in this method.

Any ideas are welcome

Upvotes: 2

Views: 715

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208944

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

You can inject UriInfo with @Context into the MessageBodyWriter. Then call uriInfo.getQueryParameter() to get the params. For example

@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");
    } 
}

Another option is to use a ContextResolver and use preconfigured ObjectMappers for different scenarios. You can also inject the UriInfo into the ContextResolver. For example

Upvotes: 1

NinePlanFailed
NinePlanFailed

Reputation: 395

You should be able to pass a list in and/or you can expose the Request object if you want to go that route.

Try ...

@Context
UriInfo uriInfo;
@Context
HttpServletRequest request;

or try altering your Rest method to something like...

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

Upvotes: 0

Related Questions