GSON disableHtmlEscaping - why GSON HTML-escapes by default in the first place?

∥☆過路亽.° 提交于 2021-02-06 15:27:29

问题


I noticed that GSON HTML-escapes < and > characters and this can be disabled by using disableHtmlEscaping() builder configuration method. But my question is - why GSON does HTML-escaping by default? What are the risks of not HTML-escaping anything?

Thanks.


回答1:


Actually, the disableHtmlEscaping() method tells Gson not to escape HTML characters such as <, >, &, =, and '.

An example in which a single quote which cause trouble: rendering unescaped JSON in a <script/> tag in an HTML page without using an additional <![CDATA[ ... ]]> tag.

Joel Leitch wrote a great response to a similar question. Here are the highlights:

Characters such as <, >, =, etc. are escaped because if the JSON string evaluated by Gson is embedded in an XHTML page then we do not know what characters are actually wrapping this JSON string. Therefore, if there was an open quote, then the embedded JSON followed by a closing quote then we do not know what will happen. Maybe if the Gson string contains a abc=123 and there happens to be a "var abc" defined then the embedded the Gson output in the page may cause the abc JavaScript variable to be assigned the value 123. The same thing can happen with < and > or even &.

As for the whitespace escaping, \t is an escaped character for a tab. Likewise, \n and \r are escape characters for newlines and carriage returns. Escaping whitespace like this should ensure that any editor will show the proper whitespace (if the editor properly evaluates these escaped characters).

The Escaper and JsonWriter classes contain more information on the complete set of characters escaped by Gson.



来源:https://stackoverflow.com/questions/23363843/gson-disablehtmlescaping-why-gson-html-escapes-by-default-in-the-first-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!