Escape forward slash in Jackson

Viewed 10716

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?

4 Answers

Kotlin version of a custom character escape for forward slashes:

/**
 * Behaves like PHP json_encode() in that forward slashes are escaped.
 */
private class PhpCompatJsonEncode : CharacterEscapes() {

    private val delegate = JsonpCharacterEscapes()
    private val escapeForSlash = SerializedString("\\/")
    private val asciiEscapes = standardAsciiEscapesForJSON()

    init {
        asciiEscapes['/'.code] = ESCAPE_CUSTOM
    }

    override fun getEscapeCodesForAscii(): IntArray {
        return asciiEscapes
    }

    override fun getEscapeSequence(ch: Int): SerializableString? {
        return when (ch) {
            '/'.code -> escapeForSlash
            else -> delegate.getEscapeSequence(ch)
        }
    }
}

This can also be configured per-writer, instead of globally in case this is only needed at a specific spot:

val writer: ObjectWriter = objectMapper.writer(PhpCompatJsonEncode())
Related