Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding quotes in JSONObject

Tags:

java

json

android

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?????

like image 486
Andrew Avatar asked Nov 16 '12 16:11

Andrew


People also ask

Is single quotes allowed in JSON?

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 .

Does JSON need double quotes?

JSON names require double quotes.

How do I skip double quotes in JSON?

if you want to escape double quote in JSON use \\ to escape it.

How do you escape double quotes in a string for JSON parser in Java?

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.


1 Answers

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?????

like image 158
Andrew Avatar answered Oct 08 '22 14:10

Andrew