Wednesday, May 5, 2021

Spring Boot: escape HTML and non-ASCII characters in Json response

Create an ObjectMapper object and let Spring Boot use our ObjectMapper object with the @Bean and @Primary annotations.

In our configuration bean:

public class MyConfiguration {
  public ObjectMapper objectMapper() {
    // create our own ObjectMapper object.
    ObjectMapper objMapper = new ObjectMapper();
    // escape all non-ASCII characters

    // definition of the HTML characters to escape
    final class HtmlCharsToEscape extends CharacterEscapes
      private final int[] asciiEscapes;
        // get the set of default escaped characters (double-quote, backslash etc)
        int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
        // and force escaping of HTML special characters:
        esc['<'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['>'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['&'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
        asciiEscapes = esc;

      @Override public int[] getEscapeCodesForAscii() {
        return asciiEscapes;

      @Override public SerializableString getEscapeSequence(int ch) {
        // no CUSTOM escaping needed:
        return null;

    // Escape the HTML special characters.
    // This will be picked up the Spring Boot.
    return objMapper; 

No comments:

Get This <