2013年9月11日 星期三

json格式字串過濾

最近使用JSon格式傳資料越來越多,也越來越常碰到特殊字元造成的問題。
乾脆一次過濾掉
∼參考網路資料改寫C#版如下:

public static string CorrectJSonString(string s)
        {
            StringBuilder sb = new StringBuilder(s.Length + 20);
            foreach (Char c in s.ToCharArray())
            {
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\"");
                        break;
                    case '\\':
                        sb.Append("\\\\");
                        break;
                    case '/':
                        sb.Append("\\/");
                        break;
                    case '\b':
                        sb.Append("\\b");
                        break;
                    case '\f':
                        sb.Append("\\f");
                        break;
                    case '\n':
                        sb.Append("\\n");
                        break;
                    case '\r':
                        sb.Append("\\r");
                        break;
                    case '\t':
                        sb.Append("\\t");
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString();
        }

沒有留言: