Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Jackson JSON do special char escaping?

Tags:

json

jackson

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

like image 822
Nikita Avatar asked Jan 12 '11 19:01

Nikita


1 Answers

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.

like image 175
StaxMan Avatar answered Oct 03 '22 01:10

StaxMan