修改 Srping MVC中 @ResponseBody 的返回内容

博主用的是Spring MVC 4.0,在项目开发过程中,觉得@ResponseBody做JSON回馈给客户端特别快。

但有时候有些属性为null,在浏览器中看着不舒服,有点暴露自己的类结构的感觉。

一直在寻找解决方案,后来找了一些是Spring 3的。

Eclipse(最好用的IDE) 最大的好处在于他是一种启发式学习的IDE,能让开发者自己去探索未知的类。

在import的时候发现有了这个类:

org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

 在3.x 的基础上做了很多改变,去网上找源码,终于找到了解决办法。

	<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
	
		<!-- 为Null的忽略 -->
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="objectMapper">
					<bean class="com.fasterxml.jackson.databind.ObjectMapper">
						<property name="serializationInclusion">
							<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
						</property>
					</bean>
				</property>
			</bean>
		</mvc:message-converters>
	
	</mvc:annotation-driven>
	
	<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<property name="favorPathExtension" value="false" />
		<property name="favorParameter" value="false" />
		<property name="ignoreAcceptHeader" value="false" />
		<property name="mediaTypes">
			<value>json=application/json</value>
		</property>
	</bean>

这样使用

    public @ResponseBody
    Map<String, Object> execute(HttpServletRequest request)

这样的方法就会很舒服了。

猜你喜欢

转载自vti-iteye.iteye.com/blog/2206073