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

star2017 1年前 ⋅ 622 阅读

我们在创建权限树的时候,经常会存在子节点,这时候就会出现循环引用,如果在使用fastjson的时候,没有做特殊的处理,那么返回给前端的json里面会出现"$ref"。前端是不能解析这个的,那我们后台必须要进行处理。

使用框架版本:springmvc4.1.6.RELEASE fastjson1.2.23

java代码:

public class TreeNodeVo implements Serializable{
   private static final long serialVersionUID = -1052589348626068068L;

   private String text;//描述
   private String id;//表id
   private List<TreeNodeVo> children;//子节点
   private String icon="none";
   private TreeStateVo state;

   get/set方法省略

}

spring-mvc.xml配置:

   <mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
				<property name="fastJsonConfig" ref="fastJsonConfig" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<bean id="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
		<property name="charset" value="UTF-8" />
		<property name="serializerFeatures">
			<list>
				<value>DisableCircularReferenceDetect</value>
			</list>
		</property>
	</bean>
	<bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
		<property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"/>
	</bean>

如果你是直接使用代码转json的,那么你看下面的代码:

   import com.alibaba.fastjson.JSON; 
   import com.alibaba.fastjson.serializer.SerializerFeature;
   
   SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;
   byte[] bytes = JSON.toJSONBytes(maps,feature);
   

是不是很简单,循环引用的问题解决了。

如有写的不对的地方,请大家指出来。

再次感谢大家耐心的看完我的博客。希望对你有帮助。


本文为博主原创文章,未经博主允许不得转载。
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: