有没有其他更好的方式:曾试过tomcat server.xml文件配置URIEncoding="utf-8",但是没有用,
现在只能这样,否则中文乱码
后端使用json数据需要:iso-8859-1 ---->>>utf-8
前端使用需要:utf--8----->>>iso-8859-1
@RequestMapping("changeCentre.action")
@RequestMapping("changeCentre.action")
public void changeCentre(
HttpServletRequest request, @RequestBody String jsonStr, HttpServletResponse response) {
String city_name = null;
try {
city_name = new String(jsonStr.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(city_name);
System.out.println(jsonStr);
try {
responseTrueOrFalse(response, new String(city_name.getBytes("utf-8"), "ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
参考GPT和自己的思路:
你可以尝试使用以下代码来将获取到的json字符串从ISO-8859-1编码改为UTF-8编码:
@RequestMapping("changeCentre.action")
public void changeCentre(HttpServletRequest request, @RequestBody String jsonStr, HttpServletResponse response) {
String city_name = null;
try {
city_name = new String(jsonStr.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(city_name);
System.out.println(jsonStr);
try {
responseTrueOrFalse(response, new String(city_name.getBytes("utf-8"), "ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
在这段代码中,我们首先将获取到的字符串从ISO-8859-1编码转换为UTF-8编码,然后再将UTF-8编码的字符串转换回ISO-8859-1编码,以便前端使用。您可以根据需要修改和调整代码以适应您的应用场景。希望这可以帮助您解决问题。