码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-04-25 17:13:36      阅读:363      评论:0      收藏:0      [点我收藏+]

标签:[1]   rcu   .net   clear   重用   san   tar   ott   isa   

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

DisableCircularReferenceDetect来禁止循环引用检测:

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

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

 

但是某些情况下并不适用,比如将值传给前端JavaScript时,就不能使用引用对象,得传原始值

"颜色": [
      {
        "$ref": "$.itemSkuList[0].itemSpecificationList[0]"
      }, 
      {
        "$ref": "$.itemSkuList[1].itemSpecificationList[0]"
      }
    ]

循环引用

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

A a = new A();
B b = new B(a);
a.setB(b);
String text = JSON.toJSONString(a); //{"b":{"a":{"$ref":".."}}}
A a1 = JSON.parseObject(text, A.class);
Assert.assertTrue(a1 == a1.getB().getA());

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

引用描述
"$ref":".." 上一级
"$ref":"@" 当前对象,也就是自引用
"$ref":"$" 根对象
"$ref":"$.children.0" 基于路径的引用,相当于 root.getChildren().get(0)

 

 

DisableCircularReferenceDetect来禁止循环引用检测:

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

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

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

标签:[1]   rcu   .net   clear   重用   san   tar   ott   isa   

原文地址:https://www.cnblogs.com/huanghongbo/p/8945378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!