使用fastjson需要注意的事项

最近在测试举报项目的单聊和群聊时,出现了"$ref": "$.data.reportContent[0].FeedInfo"这样的数据,之所以出现这样的问题是因为fastjson的JSON.toJSONString认开启了"循环引用检测"特性,加载完第一个FeedInfo对象后,当加载第二个FeedInfo对象时fastjson检测到已经加载过该对象一次了,因此不再重复加载改数据,而只是将一个指向第一个FeedInfo对象的地址赋给后面的对象,从而出现了我们看到的下面所示的数据形式。

{
    "data": {
        "handleDetail": {
            
        },"handleFeedId": "","handleReason": "","handleTime": 0,"hasHandled": 0,"illegalType": "0","pics": [
            "http://scloud.toon.mobi/f/AIvQq8lwlGH4snhbwyu7Ndib5WbC-9AS4xAiApe+WUofG.jpg"
        ],"reasonId": "16","reportContent": [
            {
                "contentOutput": {
                    "from": "c_1500459436330003","text": "不支持文件类型","type": "nonsupport","url": "http://scloud.toon.mobi/f/0T-Org7zsW6A6+V9jKji2JxevaI8ixWW4ht4nZ6ArZcfG.jpg"
                },"FeedInfo": {
                    "cardNo": "253607","FeedId": "c_1500459436330003","title": "***"
                }
            },{
                "contentOutput": {
                    "from": "c_1500459436330003","type": "nonsupport"
                },"FeedInfo": {
                    "$ref": "$.data.reportContent[0].FeedInfo"
                }
            }
        ],"reportDesc": "","reportId": "1157163647988614","reportObject": "群聊","reportPerson": [
            {
                "$ref": "$.data.reportContent[0].FeedInfo"
            }
        ],"reportTime": 1516364798614,"toonType": "100","type": 4
    },"Meta": {
        "code": 0,"message": "success"
    }
}

为了避免这种现象发生,我们在使用JSON.toJSONString时需要人为关闭"循环引用检测"特性:

String data = JSON.toJSONString(result,SerializerFeature.disableCircularReferenceDetect);
这样便可以解决该问题了。

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...