How to escape HTML in JSON

Ma Kro picture Ma Kro · Mar 28, 2015 · Viewed 20.4k times · Source

I'm wondering how can I escape HTML code in JSON ? I'm using Jackson as my JSON mapper.

In my content I have various characters: tags, single quotes, double quotes, new lines character (\n), tabs etc. I tried to use CharacterEscapes class, but with no results.

My JSON response blows up after using CharacterEscapes. I tried to escape it manually, but also without any results.

So the question is, lets say that we have:

 <p>Some text</p>\n<p>"SomeText"</p>

How can I send it back to browser as value of the JSON object?

UPDATE: Input is:

{
    "code": {
    "num": 12
},
    "obj": {
        "label": "somelabel",
        "order": 1
    },
    "det": {
        "part": "1",
        "cont": true
    },
     "html": "<p>Mine text</p>"
}

Output:

{
    "code": {
    "num": 12
},
"obj": {
    "label": "somelabel",
    "order": 1
},
"det": {
    "part":"1",
    "cont": true
},
"html":{"code": {
    "num": 12
    },
    "obj": {
        "label": "somelabel",
        "order": 1
    },
    "det": {
    "part":"
    }

Answer

Ma Kro picture Ma Kro · Mar 28, 2015

For now I have found following solution: I have added CharacterEscapes to the JsonFactory of the ObjectMapper class. Also I have changed way of writting JSON into response. Instead of

objectMapper.writeValue(response.getWriter(), myObject)

I'm doing this:

PrintWriter writer = response.getWriter();
writer.print(String.valueOf(objectMapper.writeValueAsBytes(myObject));
writer.flush();

And it works as I wanted.