Search code examples
javarestjacksongsonhateoas

What is the GSON disableHtmlEscaping equivalent in JacksonJsonProvider


I am trying to convert an URL e.g. https://api.test.com/cusomter?customer_id=1&customer_type=A

but during serialization its getting converted into https://api.test.com/customer?customer_id\u003d1\u0026customer_type\u003dA

I know that in GSON there is disableHtmlEscaping option to escape html safe conversion of = and & characters.

Can you please let know the equivalaent option in JacksonJsonProvider.


Solution

  • I found this sample code over here

    import org.codehaus.jackson.SerializableString;
    import org.codehaus.jackson.io.CharacterEscapes;
    
    // First, definition of what to escape
    public class HTMLCharacterEscapes extends CharacterEscapes
    {
        private final int[] asciiEscapes;
        
        public HTMLCharacterEscapes()
        {
            // start with set of characters known to require escaping (double-quote, backslash etc)
            int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
            // and force escaping of a few others:
            esc['<'] = CharacterEscapes.ESCAPE_STANDARD;
            esc['>'] = CharacterEscapes.ESCAPE_STANDARD;
            esc['&'] = CharacterEscapes.ESCAPE_STANDARD;
            esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
            asciiEscapes = esc;
        }
        // this method gets called for character codes 0 - 127
        @Override public int[] getEscapeCodesForAscii() {
            return asciiEscapes;
        }
        // and this for others; we don't need anything special here
        @Override public SerializableString getEscapeSequence(int ch) {
            // no further escaping (beyond ASCII chars) needed:
            return null;
        }
    }
    
    // and then an example of how to apply it
    public ObjectMapper getEscapingMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getJsonFactory().setCharacterEscapes(new HTMLCharacterEscapes());
        return mapper;
    }
    
    // so we could do:
    public byte[] serializeWithEscapes(Object ob) throws IOException
    {
        return getEscapingMapper().writeValueAsBytes(ob);
    }