使用Gson来漂亮打印JSON字符串的问题

时间:2022-09-04 21:44:58

Could someone please suggest why this is happening...

有人能告诉我为什么会这样吗?

I’ve got some code to pretty print some JSON. To do this, I am making use out of the Gson library.

我有一些代码来打印一些JSON。为此,我正在利用Gson库。

However, while thus usually works well, some characters don’t seem to be displayed properly. Here is a simple piece of code that demonstrates the problem:

然而,尽管这样做通常效果很好,但有些字符似乎没有被正确地显示出来。这里有一个简单的代码来演示这个问题:

//Creating the JSON object, and getting as String:
JsonObject json = new JsonObject();
JsonObject inner = new JsonObject();
inner.addProperty("value", "xpath('hello')");
json.add("root", inner);
System.out.println(json.toString());

//Trying to pretify JSON String:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(json.toString());
System.out.println(gson.toJson(je));

The output of the above code is:

上述代码输出为:

{"root":{"value":"xpath('hello')"}}
{
  "root": {
    "value": "xpath(\u0027hello\u0027)"
  }
}

How could I fix the above?

我怎样才能解决上面的问题呢?

1 个解决方案

#1


27  

Use this code, to create Gson object:

使用此代码创建Gson对象:

Gson gs = new GsonBuilder()
    .setPrettyPrinting()
    .disableHtmlEscaping()
    .create();

The disableHtmlEscaping() method tells gson not to escape HTML characters such as <, >, &, =, and a single quote which caused you trouble: '.

disablehtmlescape()方法告诉gson不要转义HTML字符,比如<、>、&、=,以及一个给您带来麻烦的单引号:'。

Note, that this may cause trouble, if you render such unescaped JSON into a <script/> tag in HTML page without using additional <![CDATA[ ... ]]> tag.

注意,这可能会带来麻烦,如果您在HTML页面中将这种未转义的JSON呈现为标记,而不使用额外的…标记。

You can see how it works, and what other chars are escaped, by looking into the code of JsonWriter class.

通过查看JsonWriter类的代码,您可以了解它是如何工作的,以及其他的chars是如何转义的。

#1


27  

Use this code, to create Gson object:

使用此代码创建Gson对象:

Gson gs = new GsonBuilder()
    .setPrettyPrinting()
    .disableHtmlEscaping()
    .create();

The disableHtmlEscaping() method tells gson not to escape HTML characters such as <, >, &, =, and a single quote which caused you trouble: '.

disablehtmlescape()方法告诉gson不要转义HTML字符,比如<、>、&、=,以及一个给您带来麻烦的单引号:'。

Note, that this may cause trouble, if you render such unescaped JSON into a <script/> tag in HTML page without using additional <![CDATA[ ... ]]> tag.

注意,这可能会带来麻烦,如果您在HTML页面中将这种未转义的JSON呈现为标记,而不使用额外的…标记。

You can see how it works, and what other chars are escaped, by looking into the code of JsonWriter class.

通过查看JsonWriter类的代码,您可以了解它是如何工作的,以及其他的chars是如何转义的。