When creating JSON data manually, how should I escape string fields? Should I use something like Apache Commons Lang's StringEscapeUtilities.escapeHtml
, StringEscapeUtilities.escapeXml
, or should I use java.net.URLEncoder
?
The problem is that when I use SEU.escapeHtml
, it doesn't escape quotes and when I wrap the whole string in a pair of '
s, a malformed JSON will be generated.
org.json.simple.JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.
If you are using fastexml jackson, you can use the following:
com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)
If you are using codehaus jackson, you can use the following:
org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)
Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+
Release Notes for version 3.2
LANG-797: Added escape/unescapeJson to StringEscapeUtils.
org.json.JSONObject
quote(String data)
method does the jobExtract from the documentation:
Try this
org.codehaus.jettison.json.JSONObject.quote("your string")
.Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison
Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.
If you want the string in hand: