1

我正在使用将由 Extjs 客户端使用的 Resteasy 实现一个 restfull 服务,并且我想用更多属性来装饰在 http 响应中检索到的 json 对象,而无需在服务方法中使用具有附加属性的包装类或覆盖 JacksonJsonProvider
示例:

原始对象:

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

装饰物:

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

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

我尝试使用拦截器替换将用包装器序列化的实体,但如果替换为集合的实体,它将不起作用。

有什么建议么?

4

1 回答 1

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());
        }
    }
    
于 2012-12-24T00:22:47.557 回答