您的位置:首页 > 编程语言 > Java开发

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

2015-06-03 14:58 756 查看
返回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();
} //获取写入对象
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: