spring mvc返回json

1.
@ResponseBody的注解
Spring3.0 MVC @ResponseBody的作用是把返回值直接写到HTTP response body
 
2.

第二种使用JSON工具将对象序列化成json,常用工具Jackson,fastjson,gson。

利用HttpServletResponse,然后获取response.getOutputStream()或response.getWriter()

直接输出。

 

  1. public class JsonUtil  
  2. {  
  3.       
  4.     private static Gson gson=new Gson();  
  5.   
  6.   
  7.     /** 
  8.      * @MethodName : toJson 
  9.      * @Description : 将对象转为JSON串,此方法能够满足大部分需求 
  10.      * @param src:将要被转化的对象 
  11.      * @return :转化后的JSON串 
  12.      */  
  13.     public static String toJson(Object src) {  
  14.         if (src == null) {  
  15.             return gson.toJson(JsonNull.INSTANCE);  
  16.         }  
  17.         return gson.toJson(src);  
  18.     }  
  19.  
posted @ 2016-01-09 10:53  okay4321  阅读(172)  评论(0编辑  收藏  举报