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


 

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

 

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到我的代碼片
  1.             theString = theString.Replace(">", ">");  
  2.             theString = theString.Replace("<", "&lt;");  
  3.             theString = theString.Replace(" ", "&nbsp;");  
  4.             theString = theString.Replace("\"", "&quot;");  
  5.             theString = theString.Replace("\'", "&#39;");  
  6.             theString = theString.Replace("\\", "\\\\");//對斜線的轉義   
  7.             theString = theString.Replace("\n", "\\n");  
  8.             theString = theString.Replace("\r", "\\r");  
            theString = theString.Replace(">", "&gt;");
            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