jackson jaxb annotations support in Spring

2019-08-24 02:05发布

问题:

i'm looking for the simplest way of adding jaxb annotations support to jackson. Jackson is added now to Spring by <mvc:annotation-driven/>. I need that by @ResponseBody annotation the Object is converted to xml or json dependently to the media type. I'm new in spring-mvc so doesn't understand well yet how things work. Thanks.

回答1:

Okay, I assume you want to be able to return both XML and JSON. To do this you need to create MessageConverters for both formats.

The XML message converter:

<bean id="xmlConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg>
        <oxm:jaxb2-marshaller id="jaxb2Marshaller">
            <!-- you must either bind your JAXB annotated classes here -->
            <!-- OR provide a jaxb.index and use contextPath -->
            <oxm:class-to-be-bound name="com.mycompany.MyClass"/>
        </oxm:jaxb2-marshaller>
    </constructor-arg>
    <property name="supportedMediaTypes">
        <list>
            <bean class="org.springframework.http.MediaType">
                <constructor-arg index="0" value="application"/>
                <constructor-arg index="1" value="xml"/>
                <constructor-arg index="2" value="UTF-8"/>
            </bean>
        </list>
    </property>
</bean>

The JSON message converter, which uses the JAXB annotations:

<bean id="jaxbAnnotationInspector"
    class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector"/>
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
    <property name="annotationIntrospector" ref="jaxbAnnotationInspector"/>
</bean>
<bean id="jsonConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="objectMapper">
        <bean ref="jacksonObjectMapper"/>
    </property>
    <property name="supportedMediaTypes">
        <list>
            <bean class="org.springframework.http.MediaType">
                <constructor-arg index="0" value="application"/>
                <constructor-arg index="1" value="json"/>
                <constructor-arg index="2" value="UTF-8"/>
            </bean>
        </list>
    </property>
</bean>

And finally, the AnnotationMethodHandlerAdapter, which will convert the responses to the appropriate content type, depending upon the accept headers:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="xmlConverter"/>
            <ref bean="jsonConverter"/>
        </list>
    </property>
</bean>

Note that the JAXB support in jackson isn't 100% complete or correct all the time, but the developers are really good at fixing bugs and responding to error reports.