doles
doles

Reputation: 556

how to wrap a jersey + jackson json response before being sent out

I am running Jersey 2.5.1 & Jackson in a Tomcat rest app. For my initial use case of simply transforming a POJO into JSON, the basic setup works great. Sets are nicely transformed to an json array something like this:

[{//one item},{//second item},{}... and so on]

Now, I need to inspect the result I am sending back on my rest api and
1) if it is a List or a Set, then transform it to something like:

{result:[//my original list of result objects]}


2) If it is a simple POJO, then transform it to something like this:

{result:[{//the one result object}]}

I have a feeling this should be simple to do, however, I am not finding anything that shows how to do this. Does anyone know how to do this? I have tried registering a Provider, which in turn registers an object mapper and those other approaches - none looked easy or simple... Those options looked like too much code to just wrap my objects around.

Thanks!

Upvotes: 3

Views: 1805

Answers (1)

Michal Gajdos
Michal Gajdos

Reputation: 10379

Create a Result class:

public class Result {

    private List<YourItem> result;

    // getters/setters
}

Create a WriterInterceptor that wraps your entity into Result and let Jackson to marshal the resulting object:

@Provider
public class WrappingWriterInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(final WriterInterceptorContext context)
            throws IOException, WebApplicationException {

        final Result result = new Result();
        final Object entity = context.getEntity();

        if (entity instanceof YourItem) {
            // One item.
            result.setResult(Collections.singletonList((YourItem) entity));
        } else {
            result.setResult((List<YourItem>) entity);
        }

        // Tell JAX-RS about new entity.
        context.setEntity(result);

        // Tell JAX-RS the type of new entity.
        context.setType(Result.class);
        context.setGenericType(Result.class);

        // Pass the control to JAX-RS.
        context.proceed();
    }
}

Upvotes: 4

Related Questions