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.
For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:
sends
, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if
you'd use
And now, this is also a tutorial on how to query Freebase from the command line :-)
The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:
Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
This can be compacted into
I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.
Use EscapeUtils class in commons lang API.
Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.
Apache commons-text now has a StringEscapeUtils.escapeJson(String).