详解在springmvc中解决FastJson循环引用的问题
我们先来看一个例子:
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如果发到前端是无法使用的,幸好FastJson提供了解决办法,我们来看下,解决办法为禁用循环引用检测,代码如下:
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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Spring中的NamespaceHandler与BeanDefinitionParser详解
这篇文章主要介绍了Spring中的NamespaceHandler与BeanDefinitionParser详解,由Spring启动过程之obtainFreshBeanFactory() ,可以看到NamespaceHandler、BeanDefinitionParser为解析配置文件中的Element起重要作用,那么它本身是如何被加载的呢,需要的朋友可以参考下2023-12-12
Spring Security基于散列加密方案实现自动登录功能
为了提高项目的用户体验,我们可以在项目中添加自动登录功能,当然也要给用户提供退出登录的功能。接下来学习下Spring Security基于散列加密方案实现自动登录功能,一起看看吧2021-09-09
Java中list.foreach()和list.stream().foreach()用法详解
在Java中List是一种常用的集合类,用于存储一组元素,List提供了多种遍历元素的方式,包括使用forEach()方法和使用Stream流的forEach()方法,这篇文章主要给大家介绍了关于Java中list.foreach()和list.stream().foreach()用法的相关资料,需要的朋友可以参考下2024-07-07


最新评论