fastjson中$ref的坑

相信不少人都遇到过,用fastjson进行序列化时会遇到属性出现$ref的情况,本质是fastjson在处理对象引用时默认不展开,需要自己指定序列化参数。写个DEMO演示一下:

复制代码
 1 JSONObject json = new JSONObject();
 2 JSONObject prop = new JSONObject();
 3 prop.put("name", "test");
 4 prop.put("index", "1");
 5 json.put("propA", prop);        //引用同一个对象
 6 json.put("propB", prop);        //引用同一个对象
 7 
 8 //用不同方式序列化
 9 System.out.println(JSON.toJSONString(json));
10 System.out.println(json.toJSONString());
11 System.out.println(json.toString(SerializerFeature.DisableCircularReferenceDetect));
12 System.out.println(JSON.toJSONString(json, SerializerFeature.DisableCircularReferenceDetect));
复制代码

输出结果如下:

{"propB":{"name":"test","index":"1"},"propA":{"$ref":"$.propB"}}
{"propB":{"name":"test","index":"1"},"propA":{"$ref":"$.propB"}}
{"propB":{"name":"test","index":"1"},"propA":{"name":"test","index":"1"}}
{"propB":{"name":"test","index":"1"},"propA":{"name":"test","index":"1"}}

可以看到序列化时需要加 SerializerFeature.DisableCircularReferenceDetect 才能得到正确的结果。

需要说明的是这个问题仅出现在fastjson 1.x版中,升级到fastjson 2.x后就没这个问题了,但是2.x部分API与之前不同,升级有一定的成本。

 

posted on   BoyTNT  阅读(392)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示