'Issue with Java StringEscapeUtils.escapeHtml4()

I am trying to escape a string object in my Java application using StringEscapeUtils.escapeHtml4. I am using commons-lang3-3.5.jar library.

Below is the format I am trying to do -

StringEscapeUtils.escapeHtml4("user001")

When I print in console, the output looks like- "user001"

I actually don't want my double quot to be converted into escape characters here. Because, after escaping the string, my program doesn't recognize this as valid string and I am getting malformed JSon. Is there a way to handle this or any better way? Thanks in advance.



Solution 1:[1]

Why don't you use escapeJava() instead of escapeHtml4().

escapeJava(String input)
Escapes the characters in a String using Java String rules.

It won't convert your double quotes to " but will simply escape using backslash (which is acceptable in JSON).


You can also check

escapeJson
public static final String escapeJson(String input)

Escapes the characters in a String using Json String rules.

Escapes any values it finds into their Json String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

Solution 2:[2]

The issue is not with the StringEscapeUtils.escapeHtml4(). The problem might be that you are trying to use a plain string, where your code expects JSON.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raman Sahasi
Solution 2 SaWo