Spring MVC 中如需设置Jakson的一些参数,可以这么干
<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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。