一、问题
为客户端提供的接口,其中JSON格式的字符串数据中存在"\r"\、"\n"之类的转义字符。客户端 JSON格式化时解析失败,需要服务器处理。
二、处理方式
public class Test {public static void main(String[] args) {String jsonStr = "{\"desc\": \"this is test word\r\n end\"}";jsonStr = jsonStr.replaceAll("\\r", "\\\\r");jsonStr = jsonStr.replaceAll("\\n", "\\\\n");System.out.println(jsonStr);}}
结果:'{"desc": "this is test word\\r\\n end"}'
注意:replaceAll中的第一个参数是正则表达式,所以要多加一层 \
