10

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

3
  • The virgule is a special character in JSON strings?
    – Joey
    Jan 12, 2011 at 19:41
  • Actually, whether "/" should be escaped is the better question. I assumed so from looking at this Twillio doc: twilio.com/docs/api/2010-04-01/rest/… But JSLint ain't complaining. Why is Twilio escaping "/" then in JSON responses?
    – Nikita
    Jan 12, 2011 at 19:51
  • 1
    Beats me. I can find nothing that says / needs escaping.
    – skaffman
    Jan 12, 2011 at 19:58

3 Answers 3

5

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.

1

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).

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.