fastjson把对象转化成json避免$ref

转自http://blog.csdn.net/wxwzy738/article/details/30244993

DisableCircularReferenceDetect来禁止循环引用检测:

JSON.toJSONString(..., SerializerFeature.DisableCircularReferenceDetect)

当进行toJSONString的时候,默认如果重用对象的话,会使用引用的方式进行引用对象。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. "颜色": [  
  2.       {  
  3.         "$ref": "$.itemSkuList[0].itemSpecificationList[0]"  
  4.       },   
  5.       {  
  6.         "$ref": "$.itemSkuList[1].itemSpecificationList[0]"  
  7.       }  
  8.     ]  

循环引用

很多场景中,我们需要序列化的对象中存在循环引用,在许多的json库中,这会导致stackoverflow。在功能强大的fastjson中,你不需要担心这个问题。例如:

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. A a = new A();  
  2. B b = new B(a);  
  3. a.setB(b);  
  4. String text = JSON.toJSONString(a); //{"b":{"a":{"$ref":".."}}}  
  5. A a1 = JSON.parseObject(text, A.class);  
  6. Assert.assertTrue(a1 == a1.getB().getA());  

引用是通过"$ref"来表示的

引用

描述
"$ref":".." 上一级
"$ref":"@" 当前对象,也就是自引用
"$ref":"$" 根对象
"$ref":"$.children.0" 基于路径的引用,相当于 root.getChildren().get(0)
原文地址:https://www.cnblogs.com/fangyuan303687320/p/6248527.html