java json字符串中文乱码_详解Spring MVC3返回JSON数据中文乱码问题解决

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

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 Processer

import 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

*/

@Controller

public class HomeController {

@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET)

public void writeJson(HttpServletResponse response)

{

ObjectMapper mapper = new ObjectMapper();

HashMap map = new HashMap();

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")

@ResponseBody

public Object writeJson(HttpServletResponse response)

{

ObjectMapper mapper = new ObjectMapper();

HashMap map = new HashMap();

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;

}

运行结果如下图所示:

a37ca9f8816279a70aea831536f94dbd.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值