JSON, replace quotes and slashes, but what?

I have the thankless task of creating a JSON String in Java, without any frameworks, just StringBuilder. I know this is bad, but this is only part of the prototype, I will do it better next time.

My question is: how can I put String -> "Some text WITH quotes" <- in a JSON object?

Of course, {"key" : " "Some text WITH quotes" "} not a valid json due to unselected quotes.

I think I need to use String.replace here, but what can I replace with quotes? The same question for the slash "/". What is the proper replacement?

thanks

+4
source share
4 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 Lang 2.6 or StringEscapeUtils.escapeEcmaScript() in 3.4 to do the hard work of escaping for you.

+8
source

If you want to include a literal double quote in the JSON string, you must avoid it by specifying a backslash \ . So your JSON string should look like this:

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

See json.org for the official JSON syntax.

The forward slash / not a special character and does not require escaping. The backslash \ must be escaped with itself: \\ .

Beware that Java \ also an escape character in the source code, as well as " also need to be escaped, which means that if you use them as literals in your source code, you must escape them again.

 StringBuilder sb = new StringBuilder(); sb.append("{\"key\" : \" \\\"Some text WITH quotes\\\" \""); 
+2
source
 "\\\""+"Some text WITH quotes"+"\\\"" 

-> \ "Some texts with quotes \"

escape escape char and avoid double quote in string

+1
source

With Prototype string.evalJSON (), commons-lang The StringEscapeUtils.escapeJavaScript method works fine, but with jQuery jQuery.parseJSON (string) it does not work if the string value contains apostrophes that get escaped by the above method.

The JSON string should not, strictly speaking, escape the apostrophe (== single quote character ).

Therefore, I use the StringEscapeUtils.escapeJava (String) method, which does the same as escapeJavaScript, except for the single quote character.

But it escapes Unicode characters in hexadecimal notation, which increases the length of the resulting script if the string contains many Unicode characters.

Perhaps we should use some specialized JSON libraries, such as net.sf.json.util.JSONUtils.quote (String)

0
source

Source: https://habr.com/ru/post/1397404/


All Articles