42

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

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?

Nathan
  • 8,093
  • 8
  • 50
  • 76
ricb
  • 1,197
  • 2
  • 12
  • 23

2 Answers2

67

You should enable the JsonGenerator feature which controls the escaping of the non-ASCII characters. 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"}
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
  • 2
    On java play 2.3, the import are : com.fasterxml.jackson.databind.node.ObjectNode com.fasterxml.jackson.databind.ObjectMapper – Moebius Aug 26 '14 at 13:57
  • in which package/version is JsonGenerator from? – Ajay Takur Mar 24 '23 at 16:22
  • JsonGenerator.Feature.ESCAPE_NON_ASCII Since 2.10 use JsonWriteFeature.ESCAPE_NON_ASCII instead read more - https://fasterxml.github.io/jackson-core/javadoc/2.10/com/fasterxml/jackson/core/JsonGenerator.Feature.html – Emeka Jul 14 '23 at 12:03
10

JsonGenerator is deprecated use JsonWriteFeature instead of it

 mapper.getFactory().configure(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature(), true);
Kailas010
  • 345
  • 4
  • 5