Java 使用 UTF-8 字符将 ObjectNode 写入 JSON 字符串以转义 ASCII

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

Write ObjectNode to JSON String with UTF-8 Characters to Escaped ASCII

javajsonunicodeutf-8Hymanson

提问by ricb

I would like to write the contents of Hymanson's ObjectNodeto a string with the UTF-8 characters written as ASCII (Unicode escaped).

我想将 Hymanson 的内容写入ObjectNode一个字符串,其中 UTF-8 字符写为 ASCII(Unicode 转义)。

Here is a sample method:

这是一个示例方法:

private String writeUnicodeString() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("field1", "Ma?l H?rz");
    return node.toString();
}

By default, this outputs:

默认情况下,此输出:

{"field1":"Ma?l H?rz"}

What I would like it to output is:

我希望它输出的是:

{"field1":"Ma\u00EBl H\u00F6rz"}

How can I accomplish this?

我怎样才能做到这一点?

采纳答案by Alexey Gavrilov

You should enable the JsonGenerator feature which controls the escaping of the non-ASCII characters. Here is an example:

您应该启用控制非 ASCII 字符转义的 JsonGenerator 功能。下面是一个例子:

    ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("field1", "Ma?l H?rz");
    System.out.println(mapper.writeValueAsString(node));

The output is:

输出是:

{"field1":"Ma\u00EBl H\u00F6rz"}

回答by Kailas010

JsonGenerator is deprecated use JsonWriteFeature instead of it

不推荐使用 JsonGenerator 使用 JsonWriteFeature 而不是它

 mapper.getFactory().configure(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature(), true);