Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape forward slash in Jackson

I use Jackson to generate JSON objects and write them directly into HTML's tag, like this:

   <script>
     var data = $SomeJacksonWrapper.toJson($data);
   </script>

This code breaks if some string contains '</script>' in it. Escaping forward slash (/) would solve the problem and it is alowed by JSON's spec.

How do I enable it in Jackson?

like image 300
Infeligo Avatar asked Jul 25 '11 14:07

Infeligo


1 Answers

Using StaxMan's answer, I ended up with the following code:

   public class CustomCharacterEscapes extends CharacterEscapes {

     private static final Logger log = Logger.getLogger(CustomCharacterEscapes.class);

     private final int[] _asciiEscapes;

     public CustomCharacterEscapes() {
       _asciiEscapes = standardAsciiEscapesForJSON();
       _asciiEscapes['/'] = CharacterEscapes.ESCAPE_STANDARD;
     }

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

     @Override
     public SerializableString getEscapeSequence(int i) {
       return null;
    }
  }


    public class CustomObjectMapper extends ObjectMapper {

     public CustomObjectMapper() {
       this.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes());
     }

    }
like image 120
Infeligo Avatar answered Oct 15 '22 03:10

Infeligo