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 w
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\\\" \"");
"\"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.
With Prototype's string.evalJSON(), commons-lang's StringEscapeUtils.escapeJavaScript method works fine, but with JQuery's jQuery.parseJSON(string), it doesn't work if the string value contains apostrophes which get escaped by the above mentioned method.
The JSON string shouldn't escape the apostrophe (== single quote character), strictly speaking.
So I use the StringEscapeUtils.escapeJava(String) method which does the same as escapeJavaScript except for the single-quote character.
But it escapes the unicode characters into hex notation, which augments the length of the resulting script if the string contains many unicode characters.
Maybe we should use some JSON-dedicated libraries such as net.sf.json.util.JSONUtils.quote(String)
"\\\""+"Some text WITH quotes"+"\\\""
-> \"Some text WITH quotes\"
escape the escape char and escape a double quote in string