首页 文章

如何用Resteasy装饰json响应

提问于
浏览
1

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

原始对象:

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

装饰物:

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

我发现JAXB Decorators但我无法为json类型实现装饰器 .

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

有什么建议?

1 回答

  • 1

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

    • 定义自定义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);
        }
    }
    
    • 定义过滤器类:
    @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());
        }
    }
    

相关问题