Spring in Practice

Willie Wheeler's Spring blog

Configuring Jackson to Use JAXB2 Annotations With Spring

| Comments

If you want to generate both XML and JSON views of some object, one option is to use JAXB2 annotations for the XML mapping and Jackson annotations for the JSON mapping. But that’s a little bit of a nuisance, because you have to declare the what are essentially the same mappings twice. It turns out that it’s possible to configure Jackson to use the JAXB2 annotations.

Maven configuration

First, make sure you have the jackson-xc dependency (in addition to the other Jackson dependencies) declared. This is the Maven dependency that supports using JAXB2 annotations:


Spring configuration

Next, you’ll need a bit of Spring configuration:

<oxm:jaxb2-marshaller id="marshaller">
    <oxm:class-to-be-bound name="org.skydingo.skybase.model.Person" />
    <oxm:class-to-be-bound name="org.skydingo.skybase.model.Project" />

<bean id="jaxbAnnIntrospector"
    class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
    <property name="serializationConfig.annotationIntrospector"
        ref="jaxbAnnIntrospector" />
    <property name="deserializationConfig.annotationIntrospector"
        ref="jaxbAnnIntrospector" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
            <entry key="html" value="text/html" />
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
    <property name="viewResolvers">
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
                p:suffix=".jsp" />
    <property name="defaultViews">
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"
                <property name="renderedAttributes">
            <bean class="org.springframework.web.servlet.view.xml.MarshallingView"
                p:marshaller-ref="marshaller" />

Note the use of the compound property names when injecting into the Jackson ObjectMapper. That’s a little-known but useful technique for performing injections in cases where constructor and simple property injection aren’t options.

See also