Escaping Special Characters in Kotlin (and Java)

Some characters are not supported in json. Compared to xml, json does not have a CDATA alternative, so you'll have to encode this yourself.

  • Backspace should be replaced with \b
  • Form feed should be replaced with \f
  • Newline should be replaced with \n
  • Carriage return should be replaced with \r
  • Tab should be replaced with \t
  • Double quote should be replaced with \"
  • Backslash should be replaced with with \\

The jackson ObjectMapper can be used not only to convert objects to jsonf format. It can also be used to escape simple strings.

Example

val thisShouldBeEncoded = """ "hello" """
val encoded = ObjectMapper().writeValueAsString(thisShouldBeEncoded)
println(encoded)

Output

\"hello \"