How can I get Gson's single escaping to play along with Javascript's double escaping of special characters and symbols?

StackOverflow https://stackoverflow.com/questions/22986541

Question

As a follow up on my previous question: Why doesn't my attempt to escape quotation marks in JSON work?, I would like to know if there is any way to make Gson and Javascript play along when escaping special characters and symbols.

Consider this as a database table string, that I want to display on a web page:

I am "literally" hurting inside because this do not work!

If I retrieve the string in Java from my database, and use Gson to parse it, it will look like this:

'{"text" : "I am \"literally\" hurting inside that this does not work!"}'

However, my Javascript function for parsing needs this to display it correctly:

'{"text" : "I am \\"literally\\" hurting inside that this does not work!"}'

Are there any way to fix this, other then to check for substrings in Java, and adding an extra \?

Was it helpful?

Solution

I would suggest you to use Unbescape [ http://www.unbescape.org ]

It allows you to escape JavaScript string literals (among other things like HTML, XML, JSON...), so you can pass you GSON string to it simply like:

final String escaped = JavaScriptEscape.escapeJavaScript(text);

And it will give you the JavaScript-escaped string you need.

Disclaimer, per StackOverflow rules: I'm Unbescape's author.

OTHER TIPS

Try this one, it will work in all the cases:

{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}

Sample code:

Using JSONObject:

    String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";

    try {
        System.out.println(new JSONObject(str).getString("text"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

Using Gson:

class Text implements Serializable{
    private String text;
    ...
}

Gson gson = new Gson();

String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";

System.out.println(gson.fromJson(str, Text.class).text);

Firefox Firebug plugin snapshot:

enter image description here

    String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";

    try {
        System.out.println(new JSONObject(str).getString("text"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top