jackson with jaxb

2019-03-11 12:43发布

问题:

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

回答1:

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



回答2:

You only need to use JAXB annotations if you also want to produce/consume data as XML.

If you just care about JSON, do not use JAXB annotations; there is nothing they offer over and beyond Jackson annotations. And in fact most of the time basic cases can be handled without any annotations by using Java Bean naming conventions.