Andrew
Andrew

Reputation: 21076

Padding quotes in JSONObject

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

Upvotes: 6

Views: 2579

Answers (1)

Andrew
Andrew

Reputation: 21076

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

Upvotes: 2

Related Questions