我们先来看一个例子:
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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论