您的位置:首页 > 编程语言 > Java开发

Spring集成Jackson输出非Null数据之XML配置

2014-02-25 18:12 393 查看
Spring集成Jackson之XML配置

以下为在Spring中集成Jackson输出Json数据功能,在输出数据中不包含Null数据;具体输出数据内容信息控制详见:org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

下面直接贴实现代码:

1、servlet-context.xml配置信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"> <!-- config jackson 不输出Null数据 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<beans:bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<beans:property name="objectMapper">
<beans:bean class="org.codehaus.jackson.map.ObjectMapper">
<beans:property name="serializationInclusion">
<beans:value
type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</beans:value>
</beans:property>
</beans:bean>
</beans:property>
</beans:bean>
</mvc:message-converters>
</mvc:annotation-driven>

<!-- 自动扫描com.baobaotao.web 包下的@Controller标注的类控制器类 -->
<context:component-scan base-package="com.app.*" />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>

</beans:beans>


2、Controller的写法,注意需要加 @ResponseBody:

**
* 查询列表数据
* @param request  Request
* @param response Response
* @return         ModelMap
*/
@ResponseBody
@RequestMapping("/list")
public ModelMap getList(HttpServletRequest request, HttpServletResponse response) {
ModelMap modelMap = new ModelMap() ;
try {
UserObject obj = ....;
modelMap.addAttribute(obj);
} catch(Exception e) {
e.printStackTrace();
}
return modelMap ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: