when using Jackson JSON
processor in Jersey, when and why would I need to use JAXB
annotations in between? Object->JAXB->JSON
Jackson also provides it's own JAX-RS
provider to go direct Object->JSON
. what is missing in this approach? or why would I prefer on over another
ps: I use also spring
For generating JSON you generally just have to specifiy @Produces(MediaType.APPLICATION_JSON)
. This will however take the JAXB route by default.
With Object -> JAXB -> JSON you will have to annotate the classes you want to map with @XmlRootElement
. This will work fine, but once you get to serializing a HashMap
you will not end up with an obvious {keyOne:"one",keyTwo:"two"}
but rather something strange like {entry:[{key:"keyOne",value:"one"},{key:"keyTwo",value:"two"}]}
.
So to take the direct Object -> JSON way, just specify the following in your web.xml:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
With this JSON mapping will work just the way you would expect it to work. Just don't forget to remove the @XmlRootElement
annotations, they force XML generation when POJO mapping is turned on.
Also have a look at my question regarding this: Java.util.Map to JSON Object with Jersey / JAXB / Jackson
Reference: http://jersey.java.net/nonav/documentation/latest/json.html#d4e894