首页 > 编程 > Java > 正文

详解Spring MVC3返回JSON数据中文乱码问题解决

2019-11-26 13:18:24
字体:
来源:转载
供稿:网友

查了下网上的一些资料,感觉比较复杂,这里,我这几使用两种很简单的办法解决了中文乱码问题。

Spring版本:3.2.2.RELEASE

Jackson JSON版本:2.1.3

解决思路:Controller的方法中直接通过response向网络流写入String类型的json数据。

使用 Jackson 的 ObjectMapper 将Java对象转换为String类型的JSON数据。

为了避免中文乱码,需要设置字符编码格式,例如:UTF-8、GBK 等。

代码如下:

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.fasterxml.jackson.databind.ObjectMapper; //Jsckson JSON Processerimport java.util.*;import javax.servlet.ServletOutputStream;import javax.servlet.http.*;import java.io.PrintWriter;import java.nio.charset.Charset;/** * Created with IntelliJ IDEA 12.0 * Date: 2013-03-15 * Time: 16:17 */@Controllerpublic class HomeController {  @RequestMapping(value="/Home/writeJson", method=RequestMethod.GET)  public void writeJson(HttpServletResponse response)  {    ObjectMapper mapper = new ObjectMapper();    HashMap<String,String> map = new HashMap<String,String>();    map.put("1","张三");    map.put("2","李四");    map.put("3","王五");    map.put("4", "Jackson");    String json = "";    try    {      json = mapper.writeValueAsString(map);      System.out.println(json);      //方案二      ServletOutputStream os = response.getOutputStream(); //获取输出流      os.write(json.getBytes(Charset.forName("GBK"))); //将json数据写入流中      os.flush();      //方案一      response.setCharacterEncoding("UTF-8"); //设置编码格式      response.setContentType("text/html");  //设置数据格式      PrintWriter out = response.getWriter(); //获取写入对象      out.print(json); //将json数据写入流中      out.flush();    }    catch(Exception e)    {      e.printStackTrace();    }    //return "home";  }}

还有一种方法:设置 @RequestMapping 的 produces 参数,代码如下所示:

思路:使用 @ResponseBody 注解直接返回json字符串,为了防止中文乱码,将@RequestMapping 的 produces 参数设置成"text/html;charset=UTF-8" 即可。

@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET, produces = "text/html;charset=UTF-8")@ResponseBodypublic Object writeJson(HttpServletResponse response){    ObjectMapper mapper = new ObjectMapper();    HashMap<String,String> map = new HashMap<String,String>();    map.put("1","张三");    map.put("2","李四");    map.put("3","王五");    map.put("4", "Jackson");    String json = "";    try    {      json = mapper.writeValueAsString(map);      System.out.println(json);    }    catch(Exception e)    {      e.printStackTrace();    }    return json;}

运行结果如下图所示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表