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默认开启引用检测将相同的对象写成引用的形式 默认开启引用检测将相同的对象写成引用的形式。

举个例子:

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;

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值