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与之前不同,升级有一定的成本。
分类:
开发技术
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具