简体   繁体   English

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

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

I would like to write the contents of Jackson's ObjectNode to a string with the UTF-8 characters written as ASCII (Unicode escaped).我想将 Jackson 的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?我怎样才能做到这一点?

You should enable the JsonGenerator feature which controls the escaping of the non-ASCII characters.您应该启用控制非 ASCII 字符转义的 JsonGenerator 功能。 Here is an example:下面是一个例子:

    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"}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM