Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject.toString: how NOT to escape slashes

Tags:

java

json

android

I need to send a date in JSON. The date string should look like this:

"2013/5/15"

Instead , JSONObject.toString escapes it as follows:

"2013\ /5\ /15"

I understand that this is done to allow json strings inside scripts tags, as this question explains: JSON: why are forward slashes escaped?

But in my case I don't need it. In fact the server is returning an error. The server is not dealing with this and I can't fix the server, so I must fix it in the mobile client code.

I could do a String.replace after serializing it, but what if I actually wanted to include the "\ /" string in any other part of the JSON?

Is there a way to serialize a JSON object without escaping slashes? (If possible, without escaping anything)

Thanks in advance.

like image 416
Mister Smith Avatar asked May 15 '13 11:05

Mister Smith


People also ask

How do I remove an escape character in JSON?

replaceAll("\\",""); But do note that those escape characters in no way make the JSON invalid or otherwise semantically different -- the '/' character can be optionally escaped with '\' in JSON.

Do I need to escape slash in JSON?

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required, like Harold L points out: Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out: Show activity on this post.

Why does my JSON have slashes?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON.

How do you pass a JSON object into a string in Java?

JSONObject json= (JSONObject) JSONValue. parse(jsonData); JSONObject data = (JSONObject) json. get("data"); After you have parsed the json data, you need to access the data object later get "map" data to json string.


1 Answers

I finally opted for the quick and dirty trick of replacing the escaped slashes in the serialized string before sending it to the server. Luckily, JSONObject also escapes backslashes, so i must also unscape them. Now if I wanted to send "\ /" intentionally the escaped string would be "\\/" and the result of replacing is the original string as intended.

like image 96
Mister Smith Avatar answered Sep 19 '22 16:09

Mister Smith