Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 915
ricb Avatar asked Apr 16 '14 23:04

ricb


2 Answers

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"}
like image 144
Alexey Gavrilov Avatar answered Oct 21 '22 01:10

Alexey Gavrilov


JsonGenerator is deprecated use JsonWriteFeature instead of it

 mapper.getFactory().configure(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature(), true);
like image 35
Kailas010 Avatar answered Oct 21 '22 00:10

Kailas010