fastjson把對象轉化成json避免$ref


轉: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的時候,默認如果重用對象的話,會使用引用的方式進行引用對象。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM