一 . 通过 jackson 返回JSON数据


1. 引入JAR包

  jackson-core-asl-1.9.13.jar

    jackson-core-lgpl-1.9.13.jar

    jackson-mapper-asl-1.9.13.jar

    jackson-mapper-lgpl-1.9.13.jar


2. Spring配置文件添加

 

   

   

   

 

 

 

  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

 

   

    application/json;charset=UTF-8

    text/html;charset=UTF-8

   

 

 

        

3. Controller里面修改返回值类型

@RequestMapping(value = "{username}")

public @ResponseBody  User find(@PathVariable String username, Model model, HttpServletResponse response) { 

   User u = users.get(username);

   return u;

}


二 . 通过 PrintWriter 输出字符串返回JSON数据


@RequestMapping(value = "{username}")

public void find2_1(@PathVariable String username, HttpServletResponse response) {

     Gson gson = new Gson();

     User u = users.get(username);

     String us = gson.toJson(u);

    // 需要设置编码格式,否则可能出现乱码

     response.setContentType("application/json");

     response.setCharacterEncoding("UTF-8");

     try {

          PrintWriter out = response.getWriter();

          out.print(us);

     } catch (IOException e) {

          e.printStackTrace();

     }

}