Question

I was assuming that Jackson would automatically escape special characters during serialization i.e. serialize "/path/" as "\/path\/". It appears not to be the case - at least out of the box with 1.6:

@Test
public void testJacksonSerialize() throws Exception
{
    ObjectMapper om = new ObjectMapper();
    assertEquals("\\/path\\/", om.writeValueAsString("/path/"));
}

...fails - the output produced is "/path/". Do I have to write my own serializer or is there a way to enable special char escaping in Jackson?

thanks, -nikita

Was it helpful?

Solution

Jackson only escapes mandatory things. "/" is not something you must escape, hence it is not. This as per JSON specification.

Now: if you absolutely want escaping, you can use methods to write "raw" content or values (in which case Jackson does no processing whatsoever and dumps String in output).

But do you really need such escaping? I know some generators do escape it (for reasons unknown to me), but no parser expects it so it should be just fine to leave slashes unescaped. This is different from backslashes that obviously must be escaped.

OTHER TIPS

The slash "/" doesn't need to be escaped in JSON because it has no special meaning. Yet JSON allows the slash to be escaped for the following reason.

If you dump a JSON text right into a <SCRIPT> element of an HTML text, you have to make sure that the two-character-sequence "</" does not occur in the text. That sequence would end the script element immediately according to HTML rules. But if the JSON text reads "<\/", this has the same meaning to JSON while not interferring with HTML rules. Consequently, some JSON generators escape the slash if and only if it's preceded by a less-than-sign.

That being said, I don't know the direct answer to your question (how to absolutely do the escaping in Jackson).

New line character will not work in case of Tooltip with some browsers. Not working \r\n Not working or \n Not working

Use double backslash to skip characters

Solution : use '\\r\\n' in place of '\r\n' ,
it will solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top