java 如何在 JSON 中转义 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29321240/
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-11-02 15:03:28  来源:igfitidea点击:

How to escape HTML in JSON

javajsonHymansonhtml-escape-characters

提问by Ma Kro

I'm wondering how can I escape HTML code in JSON ? I'm using Hymanson as my JSON mapper.

我想知道如何在 JSON 中转义 HTML 代码?我使用 Hymanson 作为我的 JSON 映射器。

In my content I have various characters: tags, single quotes, double quotes, new lines character (\n), tabs etc. I tried to use CharacterEscapes class, but with no results.

在我的内容中,我有各种字符:标签、单引号、双引号、换行符 (\n)、制表符等。我尝试使用 CharacterEscapes 类,但没有结果。

My JSON response blows up after using CharacterEscapes. I tried to escape it manually, but also without any results.

使用 CharacterEscapes 后,我的 JSON 响应爆炸了。我试图手动转义它,但也没有任何结果。

So the question is, lets say that we have:

所以问题是,假设我们有:

 <p>Some text</p>\n<p>"SomeText"</p>

How can I send it back to browser as value of the JSON object?

如何将其作为 JSON 对象的值发送回浏览器?

UPDATE:Input is:

更新:输入是:

{
    "code": {
    "num": 12
},
    "obj": {
        "label": "somelabel",
        "order": 1
    },
    "det": {
        "part": "1",
        "cont": true
    },
     "html": "<p>Mine text</p>"
}

Output:

输出:

{
    "code": {
    "num": 12
},
"obj": {
    "label": "somelabel",
    "order": 1
},
"det": {
    "part":"1",
    "cont": true
},
"html":{"code": {
    "num": 12
    },
    "obj": {
        "label": "somelabel",
        "order": 1
    },
    "det": {
    "part":"
    }

采纳答案by Ma Kro

For now I have found following solution: I have added CharacterEscapes to the JsonFactory of the ObjectMapper class. Also I have changed way of writting JSON into response. Instead of

现在我找到了以下解决方案:我已将 CharacterEscapes 添加到 ObjectMapper 类的 JsonFactory。我也改变了将 JSON 写入响应的方式。代替

objectMapper.writeValue(response.getWriter(), myObject)

I'm doing this:

我这样做:

PrintWriter writer = response.getWriter();
writer.print(String.valueOf(objectMapper.writeValueAsBytes(myObject));
writer.flush();

And it works as I wanted.

它可以按我的意愿工作。

回答by RE350

I would suggest to use either of below.

我建议使用以下任何一种。

1.You can use GSON library for this purpose.

1.您可以为此使用 GSON 库。

    Gson gson = new GsonBuilder().disableHtmlEscaping().create();

2.Use Apache commons StringEscapeUtils.escapeHtml("JSON string").

2.使用Apache公地StringEscapeUtils.escapeHtml("JSON string")