Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON, replace quotes and slashes, but by what?

Tags:

java

json

I have the ungrateful task to build a JSON String in Java, manually, without any framework, just a StringBuilder. I know this is bad, but it is only part of a prototype, I will do this better next time.

My question: How can I put the String -> "Some text WITH quotes" <- into a JSON object?

Of course, {"key" : " "Some text WITH quotes" "} is no valid json because of the unescaped quotes.

I think I have to use String.replace here, but by what can I replace the quotes? Same question for the slash "/". What is the proper replacement?

Thank you

like image 213
ceran Avatar asked Dec 16 '22 03:12

ceran


2 Answers

"\"Some text WITH quotes\", slashes: /foo and backslashes \\foo"

translates to:

"Some text WITH quotes", slashes: /foo and backslashes \foo

You can use StringEscapeUtils.escapeJavaScript() in apache-commons Lang 2.6 or StringEscapeUtils.escapeEcmaScript() in 3.4 to do the hard-work of escaping for you.

like image 62
Tomasz Nurkiewicz Avatar answered Dec 18 '22 17:12

Tomasz Nurkiewicz


If you want to include a literal double quote in a JSON string, you must escape it by preceding it with a backslash \. So your JSON string would have to look like this:

{"key" : " \"Some text WITH quotes\" "}

See json.org for the official JSON syntax.

The forward slash / is not a special character and does not need to be escaped. The backslash \ needs to be escaped with itself: \\.

Beware that in Java source code the \ is also the escape character and " also needs to be escaped, which means that if you use these as a literals in your source code you must escape them again.

StringBuilder sb = new StringBuilder();
sb.append("{\"key\" : \" \\\"Some text WITH quotes\\\" \"");
like image 39
Jesper Avatar answered Dec 18 '22 17:12

Jesper