json解析异常显示{“$ref“:“$[0]“}

在编写测试代码实现一个组织架构树的功能时,部门的parent部门没有显示,出现了json解析异常错误
[{“r e f " : " ref":"ref":"[0]”}] [{“r e f " : " ref":"ref":"[1]”}]

[
{"detail":"O","id":"11111","name":"网络科技公司",
"parentEntranceGuardList":[]],
{"detail":"1","id":"11113","name":"网络部",
"parentEntranceGuardList":[{"$ref":"$[0]"}],"parentId":"11111"},{"detail":"2","id":"11114","name":"网络信息安全部",
"
parentEntranceGuardList": [{"$ref":"$[1]"}],"parentId":"11113"}
]

出现r e f : " ref: "ref:"[0]"的原因 多个元素持有同一个引用。是因为循环引用对象重复,对象的hashcode是一样的,使用toString显示不同,但是用json就解析错误了
解决方案
1.取消FastJson的循环引用的检查:
SerializerFeature.DisableCircularReferenceDetect

JsONObiect.toJSONString(quardVoList.SerializerFeature.DisablecircularReferenceDetect)

也可以在项目拦截配置里加入全局禁用循环引用
但是有可能会导致StackOverflowError异常。
2. 加在字段上面 禁用循环引用

@JSONField(serialzeFeatures = {SerializerFeature.DisableCircularReferenceDetect})

3.通过对象拷贝,将对象的属性值复制新的对象中。

BeanUtils.copyProperties (old,new);

使用后 成功显示

[{"detail":"O","id":"11111","name":"网络科技公司","parentEntranceGuardList":[]},
{"detail":"1","id":"11113","name":"网络部",
"parentEntranceGuardList":[{"detail":"O","id": "11111","name":"网络科技公司","parentEntranceGuardList": []}],"parentId":"11111"}
,{"detail":"2","id":"11114","name":"网络信息安全部",
"parentEntranceGuardList": [{"detail":"1","id": "11113","name": "网络部",
"parentEntranceGuardList": [{"detail":"O","id":"11111","name":"网络科技公司","parentEntranceGuardList": [1}],""parentId":"11113"}]
}]

 

posted @ 2023-03-09 16:48  sowler  阅读(295)  评论(0编辑  收藏  举报