Gson: Problem when using toJson() to parse a java object which contains "<" or ">" in it

Created on 9 Aug 2020  路  4Comments  路  Source: google/gson

OS: mac OS Catalina(10.15.6)
JDK version: OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
Gson version: 2.8.2

when I try to use toJson() to convert a regula java class to a json string, it is found that the character "<" or ">" will be finally displayed with its Unicode: \u003c, \u0030e.

It didn't happen again when I tried another Json tool in the same environment.

It can be clamied by blow simple codes:

public class Foo {
String testStr;

public String getTestStr() {
    return testStr;
}

public void setTestStr(String testStr) {
    this.testStr = testStr;
}

}

public class TestGson {

public static void main(String[] args) {
    Gson gson = new Gson();
    Foo foo = new Foo();
    foo.setTestStr("<anyway></anyway>");
    String json = gson.toJson(foo);
    System.out.println(json);
}

}

Output: {"testStr":"\u003canyway\u003e\u003c/anyway\u003e"}

Most helpful comment

To stop Gson from escaping < and > please create the Gson object like this:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

All 4 comments

As per my understanding, the writer deliberately converts '<' and '>' to unicode to make the string HTML safe. Isn't this the intended behaviour?

To stop Gson from escaping < and > please create the Gson object like this:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

@SouradipPoddar Thanks for solution, it works. But I am still confusing that why converts '<' and '>' to unicode should be an intended behaviour.

@Jane-Eyre The idea is to generate a String that is safe to paste anywhere in HTML/XML code. Since in HTML '<' and '>' is used to represent tags, generating strings with these two won't be HTML safe.

P.S- This is my understanding. I am not a member of the project.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JakeWharton picture JakeWharton  路  39Comments

GoogleCodeExporter picture GoogleCodeExporter  路  32Comments

GoogleCodeExporter picture GoogleCodeExporter  路  20Comments

inder123 picture inder123  路  17Comments

priyankajagtap18 picture priyankajagtap18  路  14Comments