Spring MVC controller中返回json中午数据乱码,及HashMap转化json数据

本文介绍了Spring MVC中处理JSON返回中文出现乱码的问题,关键在于确保服务器与浏览器的编码格式统一,一般设置为UTF-8。此外,当JSON数据量大时,推荐使用HashMap组织数据,然后转换为JSON格式,以保持代码的清晰易读。

返回json中文乱码,是没有定义好返回数据的格式,导致服务器的编码和浏览器解析的编码不一致。所以只需要定义好返回的编码格式以及页面接收的编码格式即可。

JSP页面中定义的编码格式是:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

前台请求跨域的jsonp数据代码如下:

$.ajax({
		url:path,
		method:'get',
		data:{name:x},
		dataType:'jsonp',
		jsonp:'callback',
		jsonpCallback:'jsonpcallback',
		success:function(json){
			var addRow;
			for(var i=0;i<json.length;i++)
			{
				addRow = "<tr><td>"+json[i].name+"</td>"+"<span style="font-family: Arial, Helvetica, sans-serif;"><td>"+json[i].area+"</td>"+</span><span style="font-family: Arial, Helvetica, sans-serif;"></tr>";</span>
				$("#telesOpenSession").append(addRow);
			}
	        
		},
		error:function(){
			alert("get the teles data error");	
		}
	});

后台定义的编码格式也需要是utf-8,同时返回的json数据量很大时,使用HashMap封装,再转化为json数据,这样条理比较清晰,代码更易更改。全部代码如下:

@RequestMapping(value = "/callback",method = RequestMethod.GET)
public void callback(HttpServletResponse response,HttpServletRequest request,String name) throws Exception{
		//System.out.println(name);
		String callback=request.getParameter("callback");
		String jsonp = callback+"([";
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String,String> map = new HashMap<String,String>();
		map.put("name","丽江");
		map.put("area","1576423");
		jsonp +=mapper.writeValueAsString(map)+",";
		map.clear();
		map.put("name","大埔");
		map.put("area","435746753");
		jsonp +=mapper.writeValueAsString(map)+",";
		jsonp +="])";
		System.out.println(jsonp);
		try {
			response.setCharacterEncoding("UTF-8"); //设置编码格式
			PrintWriter out;
			out = response.getWriter();
			out.print(jsonp); //将json数据写入流中
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //获取写入对象
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值