Java removes \n, \t, \r from json

Because there is a newline character in the string, the conversion to json fails and an error is reported: json parse error.

Generally speaking, just use the replace method of string directly.

 String str = "{\"adrdet\":\"阿歌嘎\n嘎、\",\"date\":\"2023/06/06\"}";

 String s = str.replaceAll("\n", "").replaceAll("\t","");
 System.err.println("第一种去除:"+s);

If it still doesn't work at this time, you can use the following method

Pattern p = Pattern.compile("\\s*|\r|\t|\n");
Matcher m = p.matcher(str);
String parse = m.replaceAll("");
System.out.println("第二种去除:  "+parse);

\\s* represents matching whitespace characters, \r, \n represents newline characters, carriage returns, \ttab characters

These two methods can solve most problems. If that doesn't work, it may be a backslash issue.

 String s1 = str.replaceAll("\\\\n", "");
 System.out.println("反斜杠去除:"+s1);

Among them, the first slash is the escape character, the second slash is the slash itself, the third slash is the escape character, and the fourth slash is the slash itself. In Java, two backslashes and one 'n' are required to output the "\n" string. In Java's regular expressions, each of the two backslashes must be assigned a backslash for escaping. to take effect.

After the removal, the json conversion will be normal and no errors will be reported again.

Supongo que te gusta

Origin blog.csdn.net/m0_71867302/article/details/131085613
Recomendado
Clasificación