FastJson中“$ref 循环引用检测”的问题

今天在测试时,错误停留在了以下的代码行

Object object = new ObjectMapper().readValue(JSON.toJSONString(procInst.getForm()), Object.class);

报错信息:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "$ref"

查看错误日志,发现是阿里巴巴的Fastjson在转换数据出现的错误,错误中提到了$ref,了解了一下是因为在传输的数据中出现相同的对象时,fastjson默认开启引用检测将相同的对象写成引用的形式 默认开启引用检测将相同的对象写成引用的形式。

举个例子:

java 复制代码
JSONObject obj = new JSONObject();
obj.put("obj", "111");

JSONObject a = new JSONObject();
a.put("id", "a");
a.put("obj", obj);

JSONObject b = new JSONObject();
b.put("id", "b");
b.put("obj", obj);

JSONObject c = new JSONObject();
c.put("a", a);
c.put("b", b);

System.out.println(c);
//{"a":{"id":"a","obj":{"obj":"111"}},"b":{"id":"b","obj":{"$ref":"$.a.obj"}}}

System.out.println(JSON.toJSONString(c, SerializerFeature.DisableCircularReferenceDetect));
//{"a":{"id":"a","obj":{"obj":"111"}},"b":{"id":"b","obj":{"obj":"111"}}}

JSON.toJSONString使用的是com.alibaba.fastjson.JSON(错误发生在这里)

ObjectMapper使用的是jackson

亲测几种解决方式:

一、改为强转:Object object = (Object)procInst.getForm();
二、使用jackson来解析为字符:new ObjectMapper().writeBalueAsString(procInst.getForm());
三、局部关闭,使用SerializerFeature.DisableCircularReferenceDetect关闭循环引用:Object object = new ObjectMapper().readValue(JSON.toJSONString(procInst.getForm(), SerializerFeature.DisableCircularReferenceDetect), Object.class);
四、全局关闭,在SpringBoot项目的json配置中将循环引用关闭。FastJson的配置增加:fastConverter.setFeatures(SerializerFeature.DisableCircularReferenceDetect);
五、在字段的注解上,指定序列化关闭循环引用:

@JSONField(serialzeFeatures = {SerializerFeature.DisableCircularReferenceDetect})

private List<Object> objectList;
六、禁止序列化(但实际是要用的,没办法,不用的话可以禁用)

@JSONField(serialize = false)

private List<Order> orderList;

相关推荐
SimonKing29 分钟前
JetBrains 用户狂喜!这个 AI 插件让 IDE 原地进化成「智能编码助手」
java·后端·程序员
狂奔小菜鸡32 分钟前
Day39 | Java中更灵活的锁ReentrantLock
java·后端·java ee
NE_STOP13 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室18 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风20 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme20 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better20 小时前
学会与虚拟机对话---ASM
java
开源之眼1 天前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
Maori3161 天前
放弃 SDKMAN!在 Garuda Linux + Fish 环境下的优雅 Java 管理指南
java
用户908324602731 天前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot