Jul 182011
 

The ?js_string doesn’t work quite right for JSON since it ends up escaping single-quotes. This isn’t quite right for JSON since it only allows Strings to be specified using double-quotes. Therefore, in order to properly escape Strings in FreeMarker for JSON, you need to write a custom method and add it to the model. Here’s my code for a JSON escaper method:

The JSONBuilder is a class that I wrote for creating JSON using the builder pattern. However, the escape method looks like this:

Then I add this method to my model and render the template:

My templates look like this:

Jul 092010
 

I’m writing some REST WebServices that return JSON and wanted to ensure that my JSON was correctly formatted and parsable. Since the JDK ships with a JavaScript engine built into it now, I figured it would be simplest to just use that and avoid any external dependencies. Here’s my code:

Pretty simple overall. The only tricky part is that you need to add the “var obj = ” and the semicolon on the end so that the JavaScript engine can evaluate it correctly.