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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11020894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:28:20  来源:igfitidea点击:

Issues with using Gson to pretty-print JSON String

javajsongson

提问by Larry

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?

我怎样才能解决上述问题?

回答by npe

Use this code, to create Gsonobject:

使用此代码创建Gson对象:

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

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

disableHtmlEscaping()方法告诉gson不要逃避HTML字符,如<>&=,并造成你的麻烦一个单引号:'

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

请注意,如果您将此类未转义的 JSON 呈现到<script/> tagHTML 页面中而不使用其他<![CDATA[ ... ]]>标记,则这可能会导致麻烦。

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

通过查看JsonWriterclass的代码,您可以了解它是如何工作的,以及转义了哪些其他字符。