如何使用Resteasy来装饰json响应

时间:2012-04-16 01:43:55

标签: json rest jackson resteasy

我正在使用Resteasy实现一个Restfull服务,它将由Extjs客户端使用,我想在http响应中使用更多属性修饰检索的json对象,而不使用服务方法中包含其他属性的包装类或压倒JacksonJsonProvider
例如:

原始对象:

{
   "id":"1",
   "name":"Diego"
}

装饰物品:

{
   "success":"true",
   "root":{
             "id":"1",
             "name":"Diego"
          }
}

我找到JAXB Decorators但我无法为json类型实现装饰器。

我尝试使用Interceptors替换将使用包装器序列化的实体,但是如果替换作为Collection的实体则不起作用。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以编写一个拦截器,在将JSON响应传递给客户端之前将其包装起来。这是一个示例代码:

  1. 定义自定义HTTPServletResponseWrapper

    public class MyResponseWrapper extends HttpServletResponseWrapper {
        private ByteArrayOutputStream byteStream;
    
        public MyResponseWrapper(HttpServletResponse response, ByteArrayOutputStream byteStream) {
            super(response);
            this.byteStream = byteStream;
        }
    
        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    byteStream.write(b);
                }
            };
        }
        @Override
        public PrintWriter getWriter() throws IOException {
            return new PrintWriter(byteStream);
        }
    }
    
  2. 定义过滤器类:

    @WebFilter("/rest/*")
    public class JSONResponseFilter implements Filter {
    
        private final String JSON_RESPONSE = " { \"success\":\"true\", \"root\": ";
        private final String JSON_RESPONSE_CLOSE = "}";
    
        /* .. */
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
    
            // capture result in byteStream by using custom responseWrapper
            final HttpServletResponse httpResponse = (HttpServletResponse) response;
            final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            HttpServletResponseWrapper responseWrapper = new MyResponseWrapper(httpResponse, byteStream);
    
            // do normal processing but capture results in "byteStream"
            chain.doFilter(request, responseWrapper);
    
            // finally, wrap response with custom JSON
          // you can do fancier stuff here, but you get the idea
            out.write(JSON_RESPONSE.getBytes());
            out.write(byteStream.toByteArray());
            out.write(JSON_RESPONSE_CLOSE.getBytes());
        }
    }