sam
sam

Reputation: 127

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

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?

Upvotes: 4

Views: 15670

Answers (2)

David Findlay
David Findlay

Reputation: 1356

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

Upvotes: 4

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279950

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:\"}"

Upvotes: 5

Related Questions