0

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.

Rashmi Ranjan mallick
  • 6,390
  • 8
  • 42
  • 59
  • 1
    Why are you escaping HTML if you are using it in JSON? Escaping HTML is for using the string in HTML. – RealSkeptic Feb 27 '17 at 08:17
  • 1
    I was not able to reproduce your issue using the Version 3.5 of the commons-lang3. Can you share with us more details, please? – SaWo Feb 27 '17 at 08:20
  • `escapeHTML4` works fine for me and prints no quotes unless the string is `"\"user001\""` – Magnus Feb 27 '17 at 08:24

2 Answers2

0

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

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • @Raman-Thanks. I want to prevent chances of script injection inside my JSon input. What should I use in this- escapeJava() or escapeJson()? – Rashmi Ranjan mallick Feb 27 '17 at 08:40
  • @RashmiRanjanmallick they both are almost similar, with the only difference being that in Json, forward-slash (/) is escaped. You can use any of them, however, if you're intending to use it with some JSON parser, then it's better to use `escapeJson()` method. – Raman Sahasi Feb 27 '17 at 08:57
0

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.

SaWo
  • 1,515
  • 2
  • 14
  • 32
  • Thanks. I want to prevent chances of script injection inside my JSon input. Will the escapeJson() help me? – Rashmi Ranjan mallick Feb 27 '17 at 08:41
  • Can you share with us more information, please? I am interested in the part that consumes the result of the StringEscapeUtils.escapeHtml4("user001") method. – SaWo Feb 27 '17 at 08:43