jackson jaxb注释在Spring中得到支持 [英] jackson jaxb annotations support in Spring
问题描述
我正在寻找为jackson添加jaxb注释支持的最简单方法。
杰克逊现在通过< mvc:annotation-driven />
添加到Spring。我需要通过 @ResponseBody
注释将Object转换为xml或json依赖于媒体类型。
我是spring-mvc的新手,所以不太了解它是如何工作的。谢谢。
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.
推荐答案
好的,我假设您希望能够同时返回XML和JSON。为此,您需要为两种格式创建 MessageConverter
。
Okay, I assume you want to be able to return both XML and JSON. To do this you need to create MessageConverter
s for both formats.
XML消息转换器:
<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>
JSON消息转换器,它使用JAXB注释:
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>
最后, AnnotationMethodHandlerAdapter
,这将是将响应转换为适当的内容类型,具体取决于接受标头:
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>
请注意,jackson中的JAXB支持不是100%完整或正确,但是开发人员非常善于修复错误并响应错误报告。
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.
这篇关于jackson jaxb注释在Spring中得到支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!