GSON disableHtmlEscaping-为什么GSON首先默认使用HTML转义? [英] GSON disableHtmlEscaping - why GSON HTML-escapes by default in the first place?

查看:613
本文介绍了GSON disableHtmlEscaping-为什么GSON首先默认使用HTML转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到GSON HTML转义了<>字符,可以使用disableHtmlEscaping()构建器配置方法禁用它.但是我的问题是-为什么GSON默认情况下会转义HTML?不对任何HTML进行转义的风险是什么?

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?

谢谢.

推荐答案

实际上,disableHtmlEscaping()方法告诉Gson不要转义HTML字符,例如<>&='.

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

一个单引号引起麻烦的示例:在HTML页面的<script/>标签中呈现未转义的JSON,而无需使用其他<![CDATA[ ... ]]>标签.

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写了对类似问题的好评 .这些是亮点:

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

诸如<,>,=等的字符被转义,因为如果Gson评估的JSON字符串嵌入在XHTML页面中,那么我们不知道实际上是什么字符包装了该JSON字符串.因此,如果有一个开放的报价,然后是嵌入式JSON,然后是一个封闭的报价,那么我们将不知道会发生什么.也许,如果Gson字符串包含abc = 123,并且碰巧有一个"var abc",定义,然后在页面中嵌入Gson输出可能会导致abc JavaScript变量被赋值为123.和>甚至&.

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 &.

对于空格转义,\ t是制表符的转义字符.同样,\ n和\ r是换行符和回车符的转义字符.像这样转义空格应确保任何编辑器都将显示正确的空格(如果编辑器正确评估了这些转义字符).

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.

这篇关于GSON disableHtmlEscaping-为什么GSON首先默认使用HTML转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆