1. 程式人生 > >使用fastjson需要注意的事項

使用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",
                    "text": "不支援的檔案型別",
                    "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);
這樣便可以解決該問題了。