fastjson配置详解
引入依赖
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
与SpringMVC整合配置:
springmvc.xml
<!-- 开启mvc注解并设置编码格式,并且设置Fastjson支持 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"/>
</bean>
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="charset" value="UTF-8" />
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<value>QuoteFieldNames</value>
<value>WriteMapNullValue</value>
<value>WriteDateUseDateFormat</value>
<value>WriteEnumUsingToString</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Fastjson的SerializerFeature序列化属性:
- QuoteFieldNames 输出key时是否使用双引号,默认为true
- WriteMapNullValue 是否输出值为null的字段,默认为false
- WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null
- WriteNullListAsEmpty List字段如果为null,输出为[],而非null
- WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null
- WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null
- WriteDateUseDateFormat Date的日期转换器
- DisableCircularReferenceDetect 解决FastJson循环引用的问题避免出现{" r e f " : " ref":" ref":".rows[0].user"}
测试
页面:index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript">
function getUserJson() {
var url = "user/returnJson";
var args = {};
$.post(url, args, function (data) {
alert(data);
});
}
</script>
</head>
<body>
<a href="javascript:void(0)" id="returnJson" onclick="getUserJson()">Test Json</a><br>
</body>
</html>
UserController
//返回JSON
@RequestMapping("/returnJson")
@ResponseBody
public Collection<User> returnJson(){
Map<Integer, User> us = new HashMap<Integer, User>();
us.put(1, new User("lisi", "123456", new Address("江苏", "扬州")));
us.put(2, new User("lisi", "123456", new Address("江苏", "扬州")));
us.put(3, new User("lisi", "123456", new Address("江苏", "扬州")));
return us.values();
}