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
Issues with using Gson to pretty-print JSON String
提问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 Gson
object:
使用此代码创建Gson
对象:
Gson gs = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
The disableHtmlEscaping()
method tellsgson
not 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/> tag
in HTML page without using additional <![CDATA[ ... ]]>
tag.
请注意,如果您将此类未转义的 JSON 呈现到<script/> tag
HTML 页面中而不使用其他<![CDATA[ ... ]]>
标记,则这可能会导致麻烦。
You can see how it works, and what other chars are escaped, by looking into the code of JsonWriter
class.
通过查看JsonWriter
class的代码,您可以了解它是如何工作的,以及转义了哪些其他字符。