特殊字符導致json字符串轉換成json對象出錯


在對數據庫取出來的數據(特別是描寫敘述信息)里面含有特殊字符的話。使用JSON.parse將json字符串轉換成json對象的時候會出錯,主要是雙引號,回車換行等影響明顯,左尖括號和右尖括號也會導致顯示問題,所以要在輸出到頁面進行json對象轉換之前將一些特殊符合進行編碼或轉義,以下展示的是C#代碼編碼和轉義幾個經常使用特殊字符。經過筆者測試,將這些符號編碼和轉義之后,大部分json字符串都能夠轉換成json對象了。假設遇到個別問題,應朝着這個方向去查找問題。

            theString = theString.Replace(">", ">");
            theString = theString.Replace("<", "&lt;");
            theString = theString.Replace(" ", "&nbsp;");
            theString = theString.Replace("\"", "&quot;");
            theString = theString.Replace("\'", "&#39;");
            theString = theString.Replace("\\", "\\\\");//對斜線的轉義
            theString = theString.Replace("\n", "\\n");
            theString = theString.Replace("\r", "\\r");

注意:\r是回到行首。\n是新啟一行,這兩個一般同一時候出現,應該同一時候處理。


補充:文字中間的換行,空格在數據庫里面不以\r\n,&nbsp;;等形式顯示出來(“本書”與“前80”之間換行。“由”與“曹雪芹”之間空格)

文字:


數據庫:



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM