tags:

views:

113

answers:

2

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.

+4  A: 

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

Thanatos
Is it valid in JSON, like in JavaScript, to enclose strings in double quotes or single quotes? Or is it only valid to enclose them in double quotes?
Bytecode Ninja
Only double quotes (`"`).
Thanatos
+1  A: 

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.

Vladimir
By manually I meant not by using a JSON library like Simple JSON, Gson, or XStream.
Bytecode Ninja
Just a matter of curiosity -- why wouldn't you want to use one of these APIs? It's like trying to escape URLs manually, instead of using URLEncode/Decode...
Vladimir