Spring使用Jackson过滤!JSON
一、问题的提出。
项目使用Spring MVC框架,并用jackson库处理JSON和POJO的转换。在POJO转化成JSON时,希望动态的过滤掉对象的某些属性。所谓动态,是指的运行时,不同的controler方法可以针对同一POJO过滤掉不同的属性。
以下是一个Controler方法的定义,使用@ResponseBody把获得的对象列表写入响应的输出流(当然,必须配置jackson的MappingJacksonHttpMessageConverter,来完成对象的序列化)
其中pointcut的expression能够匹配到目标类的方法。
在doAround方法中,需要获得当前引用的HttpResponse对象,因此使用以下方法解决:
创建一个WebContext工具类:@Component("webContextFilter")public class WebContextFilter implements Filter {public void init(FilterConfig filterConfig) throws ServletException { }public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) resp;ServletContext servletContext = request.getSession().getServletContext();WebContext.create(request, response, servletContext);chain.doFilter(request, response);WebContext.clear();}@Overridepublic void destroy() {// TODO Auto-generated method stub}}
别忘了在web.xml中增加这个filter。
OK,It is all。
四、总结
设计的一些要点:
1、要便于程序员使用。程序员根据业务逻辑需要过滤字段时,只需要定义个"Filter“,然后使用注解引入该Filter。
2、引入AOP来保持原来的REST风格。对于项目遗留的代码,不需要进行大幅度的修改,只需要增加注解来增加对过滤字段的支持。
仍需解决的问题:
按照目前的设计,定义的Filter不支持继承,每一种动态字段的业务需求就会产生一个Filter类,当类数量很多时,不便于管理。
五、参考资料
http://www.cowtowncoder.com/blog/archives/cat_json.html
http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring