I'm building a JSON string to send to my web service. Since one of the pieces is user-inputted, there is the possibility for double quotes. I'm trying to resolve the issue by escaping it.
String strValue = "height of 6\"";
JSONObject json = new JSONObject();
json.put("key", strValue.replaceAll("\"","\\\""));
The problem here is when I do json.toString()
, I get 3 slashes.
Ex:
{"key","height of 6\\\""}
If I don't try to do any replacing, json.toString()
gives me broken json.
Ex:
{"key", "height of 6""}
How can I do this correctly?
Note: When my website saves this value and displays it, it displays height of 6\"
UPDATE:
It appears the culprit is json.toString()
When I call the replaceAll
method it -- correctly -- only escapes the double quote. It appears json.toString()
escapes slashes. To fix the issue, I must do json.toString().replace("\\\\", "")
. This begs the question: Why on Earth does JSONObject escape slashes and not double quotes?????
Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .
JSON names require double quotes.
if you want to escape double quote in JSON use \\ to escape it.
You can escape String in Java by putting a backslash in double quotes e.g.” can be escaped as\” if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quotes with escape character for even a medium size JSON is time taking, boring, and error-prone.
It appears the culprit is json.toString()
When I call the replaceAll method it -- correctly -- only escapes the double quote. It appears json.toString()
escapes slashes. To fix the issue, I must do json.toString().replace("\\\\", "")
.
This begs the question: Why on Earth does JSONObject escape slashes and not double quotes?????
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With