天天看點

SpringMVC--使用fastjson配置詳解

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();
    }
           
SpringMVC--使用fastjson配置詳解

繼續閱讀