Jackson removes backslash from java string, is it correct?

18 views
Skip to first unread message

Никита

unread,
Jun 17, 2021, 12:29:25 PM6/17/21
to jackson-user

I need to parse json using jackson:

String string = "{\"field\" : \" \\/ \"}";

JsonNode node = new ObjectMapper().readTree(string);
 String result = node.toString();
 System.out.println(result);

I expect this kind of output:   

result == {"field":" \/ "}

But, I end up with:

result == {"field":" / "}

How can I receive output like this?

result == {"field":" \/ "}

Tatu Saloranta

unread,
Jun 17, 2021, 1:06:47 PM6/17/21
to jackson-user
This seems to be working as expected: Java compiler replaces "\\" in
input String with single "\", and then in JSON String "\" is taken to
mean JSON escaping so "\/" is decoded as "/".
It might make sense to construct JsonNode value instead of raw JSON
escaped String since then all escaping would be handled by Jackson --
but if you must pass a String that contains JSON, you will need to use
more escaping.
Something like:

String string = "{\"field\" : \" \\\\/ \"}";

(two "\"s for Javac, and then two of those for JSON escaping)

Constructing JsonNode on the other hand would be

ObjectNode n = mapper.createObjectNode();
n.put("field", "\\/"); // still need doubling for javac

-+ Tatu +-
Reply all
Reply to author
Forward
0 new messages