【问题标题】:how to wrap a jersey + jackson json response before being sent out如何在发送之前包装球衣 + 杰克逊 json 响应
【发布时间】:2014-02-13 00:50:03
【问题描述】:

我在 Tomcat 休息应用程序中运行 Jersey 2.5.1 & Jackson。对于我最初将 POJO 转换为 JSON 的用例,基本设置非常有效。集合很好地转换为 json 数组,如下所示:

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

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

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


2) 如果是简单的 POJO,则将其转换为如下形式:

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

我觉得这应该很容易做到,但是,我没有找到任何说明如何做到这一点的东西。有谁知道如何做到这一点?我已经尝试注册一个提供者,它反过来注册一个对象映射器和其他方法 - 没有一个看起来简单或简单......这些选项看起来像太多的代码来包装我的对象。

谢谢!

【问题讨论】:

    标签: jackson jersey-2.0


    【解决方案1】:

    创建一个Result 类:

    public class Result {
    
        private List<YourItem> result;
    
        // getters/setters
    }
    

    创建一个 WriterInterceptor 将您的实体包装到 Result 中并让 Jackson 编组生成的对象:

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

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 2015-01-15
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多