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?
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With