详解在springmvc中解决FastJson循环引用的问题

2025-05-29 0 25

我们先来看一个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
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));

}

}

输出:

?

1
{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}

可以看到,这个json如果发到前端是无法使用的,幸好FastJson提供了解决办法,我们来看下,解决办法为禁用循环引用检测,代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
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));

}

}

输出如下:

?

1
{"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}

问题是如果我们在spring mvc中使用的时候,需要将SerializerFeature注入到MessageConverter里面,FastJsonHttpMessageConverter

但是SerializerFeature是一个enum类型的,又是一个array,考虑到大部分人对这个不熟悉,直接上代码了。

?

1

2

3

4

5

6

7

8

9

10

11

12
<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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://asialee.iteye.com/blog/2101915

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解在springmvc中解决FastJson循环引用的问题 https://www.kuaiidc.com/118765.html

相关文章

发表评论
暂无评论