By Jakub Podlesak-Oracle on Feb 13, 2009
This is an update for a tech tip on configuring JSON in Jersey, which i wrote in October 2008. The way of JSON configuration, suggested in the tech tip, is now deprecated (but still functioning). Here i would like to describe the new API, which will hopefully last (and be supported) a way longer.
Notice: you will need to bundle
with your application in order to take advantage of the recently added JSON NATURAL convention
Configuring JSON format, as described in the tech tip, meant to implement a
class returning an instance of
JSONJAXBContext. This principle have not changed.
What changed is a way, how the
JSONJAXBContext itself is being configured.
Lets look at the sample code below (using the deprecated API):
There you needed to create a property bag, put appropriate configuration options into it,
and then pass it to the
Jersey 1.0.2 JSON Configuration
In the currently available 1.0.2 Jersey version, a new
JSONConfiguration class was introduced to became a central point for JSON configuration options.
For creating a new
JSONConfiguration instance, a builder pattern is employed.
It is not only more user friendly, but also ensures only meaningful JSON options could be combined together.
You can compare the following code, with the deprecated example above:
You can look at
JSONConfiguration javadoc for detailed information on various configuration options.
If you go a bit further, you can ask if the configuration could be simplified even more. Imagine you have much bigger number of JAXB beans in your model, and they are more complex. It could easily become unmanageable to maintain a reasonable JSON configuration as described so far. Then if you happen to have conflicting non-string/string values and/or arrays/non-arrays elements in your set, you could easily run out of options there.
A natural way to overcome above mentioned issues, is to simply use recently introduced Jersey
NATURAL JSON notation. Then you need only to:
Such configuration is simple from user point of view, but yet very powerful. You do not need to keep various configuration options in sync with your actual JAXB beans, and be worried what options to actually use (what exact names, etc.). Jersey will automatically take care about serializing Java collections/arrays as JSON arrays, Java booleans as JSON booleans, Java ints as JSON integers,and so on.