本文介绍了使用Gson漂亮地打印JSON字符串的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有人可能会建议为什么会发生这种情况...... 我有一些代码可以打印一些JSON。为此,我正在使用 Gson图书馆。 然而,虽然通常效果不错,但某些角色似乎并没有正确显示。这是一段简单的代码,它演示了这个问题: //创建JSON对象并获取字符串: JsonObject json = new JsonObject(); JsonObject inner = new JsonObject(); inner.addProperty(value,xpath('hello')); json.add(root,inner); System.out.println(json.toString()); //尝试提供JSON字符串: Gson gson = new GsonBuilder()。setPrettyPrinting()。create(); JsonParser parser = new JsonParser(); JsonElement je = parser.parse(json.toString()); System.out.println(gson.toJson(je)); 以上代码的输出是: {root:{value:xpath('hello')}} {root:{值:xpath(\\\'hello\\\')} } 使用这段代码,创建 Gson code> object: pre $ g $ g $ gson = new GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create(); disableHtmlEscaping()方法告诉 gson 不能转义HTML字符,如< ,> ,& , = ,以及一个引起麻烦的单引号: 。 注意,如果您将这样未转义的JSON呈现为< script /> 标签在HTML页面中不使用额外的<![CDATA [...]]> 标签。 通过查看 JsonWriter class 。 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.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? 解决方案 Use this code, to create Gson object: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: '.Note, that this may cause trouble, if you render such unescaped JSON into a <script/> tag in HTML page without using additional <![CDATA[ ... ]]> tag.You can see how it works, and what other chars are escaped, by looking into the code of JsonWriter class. 这篇关于使用Gson漂亮地打印JSON字符串的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 09:39