This website uses cookies to ensure you get the best experience. Learn More.
Working with JSON in Freemarker
Freemarker has some nice native support for working with JSON. And with the help of a few Liferay utility classes, it's very easy to even consume JSON web services from Freemarker. Note: you can view all of the example code on github: https://github.com/allen-ziegenfus/dev-playground/tree/master/freemarker
Freemarker hashes and sequences can be created from literal JSON strings as follows:
Output:
Salmon
Pizza with Taleggio
But what if we have JSON in a String object? In this case there are a couple approaches:
Using ?eval on a String that includes JSON will convert it like a literal to a Freemarker hash. As the name implies, Freemarker also evaluates any expressions in the String, which may or may not be what you want. For example, the reference ${name} is resolved, so the word "junk" appears in the output, even though it is not resolved through the assign tag (here I explicitly broke up the reference to show that ?eval is resolving it):
With the jsonFactoryUtil we can also pass a JSON string and get a JSONObject. This will not resolve any references (so no "junk"), but has the downside that we can't use expression language references with the resulting object. Instead we have to use the JSONObject methods like getString:
The deserialization methods of jsonFactoryUtil will return back an object that is apparently automagically mapped to a Freemarker hash. This makes referencing even nested JSON data easy and "natural", and you can also use the standard Freemarker operators to check for values or provide default values (!):
To go the other direction we can also use our friend jsonFactoryUtil. In this case I instantiate a Freemarker hash with a literal, and then output the JSON to the browser console.
Finally, these techniques can be combined with using the httpUtil to pull JSON data from external services and create markup in Freemarker. Here is an example using the "Beer" api at https://punkapi.com/