如果项目的编码为GBK的话,就会导致json数据传入后台时接受的为乱码,在这里我分享一下我这次的跳坑经历;
项目编码:GBK
问题现象:
1:Filter中已经过滤了编码设置
2:不管在$.ajax({})中是否设置contentType,及如何设置,都会出现乱码
解决方案:
1.前台组装json数组push时使用encodeURI()进行编码,例如:
var rejectAry = new Array();
var rejectInfo = {
"schemaNo":$("#hSchemaNo").val(),
"fundCode":$("#hFundCode").val(),
"rejectDesc":$("#rejectDesc").val()
};
rejectAry.push(encodeURI(JSON.stringify(rejectInfo)));
2.后台使用 URLDecoder.decode(request.getParameter("rejectAry"),"UTF-8") 以utf-8解码,例如
JSONArray rejectInfoArray = null;
try {
rejectInfoArray = JSONArray.fromObject(URLDecoder.decode(request.getParameter("rejectAry"),"UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
List<RejectInfo> rejectInfoList = JSONArray.toList(rejectInfoArray, new RejectInfo(), new JsonConfig());