I'm facing issues while parsing JSON strings with Jackson in some cases.
String jsonString = "{\"Age\":40, \"Name\":\"Sample User\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonString,JsonNode.class);
System.out.println(jsonstirng)
{"Age":40, "Name":"Sample User"}
The above code works well when I pass the jsonString
value.
In some cases, I need to escape invalid string characters like ",'
etc
For escaping I am using Apache StringEscapeUtils
.
String escapedString = StringEscapeUtils.escapeJson(jsonStirng);
Escaped String output
{\"Age\":40,\"Name\":\"Sample User\"}
When I pass the escaped string to mapper
its throws an Unexpected character exception.
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(escapedString,JsonNode.class);
Exception
Unexpected character ('\' (code 92)): was expecting double-quote to start field name
Actually, I'm parsing ModSecurity audit logs. The response body of the audit log has (HTML, CSS, javascript, etc) stuff that's why I need to escape the JSON string other wise its breaks the JSON format.