<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="featuresToEnable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE" /> </array> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
解释,上面那这个例子是我实际的配置节选,配置输出json时把对象作为根元素。通过配置jackson的SerializationFeature.WRAP_ROOT_VALUE来达到目的。
Spring MVC默认配置就只需一个 <mvc:annotation-driven\>,文档( http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html#mvc-config-enable )里说了会加载一大串converter,而Jackson有很多配置项,要达到能够自由配置Jackson的目的,按照参考资料 1. 里的内容,我们还可以做如下配置。
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:autoDetectFields="false" p:autoDetectGettersSetters="false" p:annotationIntrospector-ref="jaxbAnnotationIntrospector" /> </property> </bean>
或者
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:failOnEmptyBeans="false" p:indentOutput="true"> <property name="serializers"> <array> <bean class="org.mycompany.MyCustomSerializer" /> </array> </property> </bean> </property> </bean>
如果没有可直接用的setter属性
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="featuresToEnable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature$WRAP_ROOT_VALUE"/> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature$CLOSE_CLOSEABLE"/> </array> </property> <property name="featuresToDisable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature$USE_ANNOTATIONS"/> </array> </property> </bean>
进而用自定义Module来配置 ObjectMapper
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/> </bean>
时间: 2024-10-29 16:04:33