js java 编码 解码 解决特殊符号json转义不了问题

阅读更多
开发中碰到问题,记录一下解决方法:
页面输入的信息包含特殊字符如<>等等,在json解析的时候抛出异常如下:
org.codehaus.jackson.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
at [Source: java.io.StringReader@7f7d2d70; line: 1, column: 285]

解决办法:js里编码,java代码里再解码
JS:
var tool_desc = $.trim($(".add_field .tool_desc").val());
if(null != tool_desc && "" != tool_desc){
tool_desc = encodeURI(tool_desc);//编码  防止<>json转义不了
}

JAVA:
String tool_desc = StringUtils.parseString(param.get("tool_desc"));
if(null != tool_desc && !"".equals(tool_desc.trim())){
tool_desc = URLDecoder.decode(tool_desc);//解码 防止<>json转义不了
}

你可能感兴趣的:(js,java,编码,解码,json解析不了<>)