How to escape or remove "\" from the gson generated string?

12,129

Solution 1

Based on comments on your question, the object parameter is actually referencing a Java String with the value

{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}

I can't say why, but that's what your String contains.

String is a special type which Gson interprets as a JSON string. Since " is a special character that must be escaped in JSON strings, that's what Gson does and produces the JSON string.

"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"

Solution 2

The \ character is escaping special characters like " in the string. You can't store a " in a string without a leading . It has to be \".

You remove the slashes when you display any output string.

Apache Commons has a library for handling escaping and unescaping strings: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Share:
12,129
sam
Author by

sam

Updated on July 17, 2022

Comments

  • sam
    sam almost 2 years

    I am loading a value from the property file and then passing it to gson method for converting it to final json object. However, the value coming from the property file has double quotes for which the gson is adding "\" to the output. I have scanned down the whole web but unable to find a solution

    The property file contains

    0110= This is a test for the renewal and the "Renewal no:" 
    

    Here's my code

    public String toJSONString(Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        //Note object here is the value from the property file
        return gson.toJson(object);
    }
    

    This produces

    "{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
    

    I am not sure in the output, why it is adding or wrapping the \ around the literals or where ever we have the double quotes in the property file value?