1. 程式人生 > >C# ASP.NET替換要轉化為json的資料中的特殊符號

C# ASP.NET替換要轉化為json的資料中的特殊符號

替換要轉化為json的資料中的特殊符號

1.   分析和解決

1.1    問題分析

當我們將資料庫中的資料讀取出來,轉換為json資料的時候,中間可能會遇到這樣的事情:資料庫中的某些欄位中的值有些特殊字元(例如:”、’、\等等)。如果在轉換為json資料之前不替換的話,json可能不能驗證通過,從而影響你接下來的工作。

1.2    問題解決

我這裡採用一種替換轉義的方式來修改資料:

/// <summary>

         ///   替換部分字串

         /// </summary>

         /// <param name="sPassed">需要替換的字串</param>

         /// <returns></returns>

         private static string ReplaceString(string sContent)

         {

             if (sContent == null) { return sContent; }

             if (sContent.Contains("\\"))

             {

                 sContent = sContent.Replace("\\", "\\\\");

             }

             if (sContent.Contains("\'"))

             {

                 sContent = sContent.Replace("\'", "\\\'");

             }

             if (sContent.Contains("\""))

             {

                 sContent = sContent.Replace("\"", "\\\"");

             }

             //去掉字串的回車換行符

             sContent = Regex.Replace(sContent, @"[\n\r]", "");

             sContent = sContent.Trim();

             return sContent;

         }

將源資料中的’、”、\\、空格、換行等都替換成轉義符,這樣你拼接的json資料就是正常的,顯示出來格式和資料庫中的一樣。

1.3     分享

這只是一種處理“包含特殊字元的資料轉換為json資料”的方法。俗話說:條條道路通羅馬。如果你們有其他的方法,謝謝來分享!