在被送出之前如何包裹球衣+杰克逊json的反应

时间:2014-01-22 19:10:46

标签: jackson jersey-2.0

我正在运行Jersey 2.5.1&杰克逊在Tomcat休息应用程序。对于我简单地将POJO转换为JSON的初始用例,基本设置非常有效。集很好地转换为像这样的json数组:

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

现在,我需要检查我在休息api上发回的结果
1)如果它是List或Set,则将其转换为类似:

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


2)如果它是一个简单的POJO,那么把它转换成这样的东西:

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

我觉得这应该很简单,但是,我没有找到任何显示如何做到这一点。有谁知道如何做到这一点?我已经尝试注册一个Provider,它依次注册一个对象映射器和其他方法 - 没有一个看起来简单或简单......这些选项看起来像是太多的代码来包裹我的对象。

谢谢!

1 个答案:

答案 0 :(得分:4)

创建Result类:

public class Result {

    private List<YourItem> result;

    // getters/setters
}

创建一个WriterInterceptor,将您的实体包装到Result中,让杰克逊编组生成的对象:

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