Fastjson-fastjson中$ref对象重复引用问题:二
import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; /** * fastjson中$ref对象重复引用问题 * * 介绍: * FastJson提供了SerializerFeature.DisableCircularReferenceDetect这个序列化选项,用来关闭引用检测。 * 关闭引用检测后,重复引用对象时就不会被$ref代替,但是在循环引用时也会导致StackOverflowError异常。 * * 用法: * JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); */ public class TestFastJson { List<Person> list = new ArrayList<Person>(); Person p = new Person("ZhangSan", 23); /** * 测试main */ public static void main(String[] args) { // new TestFastJson().test1(); new TestFastJson().test2(); } /** * 未关闭引用检测,转化字符串时会出现$ref */ public void test1() { list.add(p); list.add(p); String jsonStr = JSON.toJSONString(list); System.out.println(jsonStr); // [{"age":23,"name":"ZhangSan"},{"$ref":"$[0]"}] } /** * 关闭引用检测后,$ref的问题就会被解决 */ public void test2() { list.add(p); list.add(p); String jsonStr = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect); System.out.println(jsonStr); // [{"age":23,"name":"ZhangSan"},{"age":23,"name":"ZhangSan"}] } } class Person { private String name; private int age; // 构造函数 public Person(String name, int age) { super(); this.name = name; this.age = age; } // getters/setters(略) }
https://www.cnblogs.com/zj0208/p/6196632.html