com.alibaba.fastjson.JSONObject循環給同一對象賦值會出現"$ref":"$[0]"現象問題


1.今天定義了一個JSONObject對象,引用的com.alibaba.fastjson.JSONObject,循環給這個對象賦值出現"$ref":"$[0]"現象,

/** * fastjson中$ref對象重復引用問題 * * 介紹: * FastJson提供了SerializerFeature.DisableCircularReferenceDetect這個序列化選項,用來關閉引用檢測。 * 關閉引用檢測后,重復引用對象時就不會被$ref代替,但是在循環引用時也會導致StackOverflowError異常。 * * 用法: * JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); */

一個集合中,給相同的對象循環賦值時,它會認為是一個對象,就出現$ref
舉例:
 1 2 
 3 import com.alibaba.fastjson.JSONArray;
 4 import com.alibaba.fastjson.JSONObject;
 5 
 6 public class test {
 7 
 8     public static void main(String[] args) {
 9         JSONObject json = new JSONObject();
10         JSONArray array = new JSONArray();
11         for(int i=0;i<3;i++){
12             json.put("id",i);
13             array.add(json);
14             System.out.println(array);
15         }
16         System.out.println(array);
17     }
18 }
上面的例子就會出現這個現象。(但是如果把JSONObject json = new JSONObject();放到for循環之內就不會出現,因為每次循環都會新建一個對象,彼此不一樣)

正確的做法之一為,關閉檢測,更改之后,
 1  2 
 3 import com.alibaba.fastjson.JSON;
 4 import com.alibaba.fastjson.JSONArray;
 5 import com.alibaba.fastjson.JSONObject;
 6 import com.alibaba.fastjson.serializer.SerializerFeature;
 7 
 8 public class test {
 9 
10     public static void main(String[] args) {
11         JSONObject json = new JSONObject();
12         JSONArray array = new JSONArray();
13         for(int i=0;i<3;i++){
14             json.put("id",i);
15             String str = JSON.toJSONString(json, SerializerFeature.DisableCircularReferenceDetect);
16             JSONObject jsonjson = JSON.parseObject(str);
17             array.add(jsonjson);
18             System.out.println(array);
19         }
20         System.out.println(array);
21     }
22 }

 

這個SerializerFeature.DisableCircularReferenceDetect就是關閉引用檢測,就不會出現$ref了

2.當然也可以吧JSONObject初始化放到for循環內,這樣就不用關閉檢測了。

操作網址:https://www.cnblogs.com/zj0208/p/6196632.html

自己的思路做個記錄,如果侵權,請聯系刪除


免責聲明!

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



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