詳解在springmvc中解決FastJson循環(huán)引用的問題
更新時間:2017年01月23日 15:25:38 作者:asialee
本篇文章主要介紹了在springmvc中解決FastJson循環(huán)引用的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
我們先來看一個例子:
package com.elong.bms; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; public class Test { public static void main(String[] args) { Map<String, Student> maps = new HashMap<String, Student>(); Student s1 = new Student("s1", 16); maps.put("s1", s1); maps.put("s2", s1); byte[] bytes = JSON.toJSONBytes(maps); System.out.println(new String(bytes)); } }
輸出:
{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}
可以看到,這個json如果發(fā)到前端是無法使用的,幸好FastJson提供了解決辦法,我們來看下,解決辦法為禁用循環(huán)引用檢測,代碼如下:
package com.elong.bms; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class Test { public static void main(String[] args) { Map<String, Student> maps = new HashMap<String, Student>(); Student s1 = new Student("s1", 16); maps.put("s1", s1); maps.put("s2", s1); SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect; byte[] bytes = JSON.toJSONBytes(maps,feature); System.out.println(new String(bytes)); } }
輸出如下:
{"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}
問題是如果我們在spring mvc中使用的時候,需要將SerializerFeature注入到MessageConverter里面, FastJsonHttpMessageConverter
但是SerializerFeature是一個enum類型的,又是一個array,考慮到大部分人對這個不熟悉,直接上代碼了。
<bean id="jsonConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=UTF-8"/> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <value>DisableCircularReferenceDetect</value> </array> </property> </bean> <bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"> <property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property> </bean>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PageHelper在springboot+mybatis框架中的使用步驟及原理解析
這篇文章主要介紹了PageHelper在springboot+mybatis框架中的使用步驟及原理解析,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03springboot+springmvc實現(xiàn)登錄攔截
這篇文章主要介紹了springboot+springmvc實現(xiàn)登錄攔截,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10