Ref: 剑飘江湖的博客 – JSON格式数据中特殊字符的处理
public static String stringToJson(String s) {
if (StringUtils.isEmpty(s)) {
return s;
}
StringBuffer sb = new StringBuffer ();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"':
sb.append("\"");
break;
/*case '\':
sb.append("\\");
break;
case '/':
sb.append("\/");
break;*/
case 'b':
sb.append("\b");
break;
case 'f':
sb.append("\f");
break;
case 'n':
sb.append("\n");
break;
case 'r':
sb.append("\r");
break;
case 't':
sb.append("\t");
break;
default:
sb.append(c);
}
}
return sb.toString();
}