日期:2014-05-17  浏览次数:20453 次

后台拼接json字符串,其中包含后台的编辑器的内容,如何写呢?
比如{"newscontent":"这里是从数据库里读取出来的编辑器里的内容"}

在生成JSON以后总是出错,这个是需要转义的吗,需要转哪些呢>?

------解决方案--------------------
C# code

    /// <summary>
    /// Encodes a string to be represented as a string literal. The format
    /// is essentially a JSON string.
    /// 
    /// The string returned includes outer quotes 
    /// Example Output: "Hello \"Rick\"!\r\nRock on"
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string EncodeJsString(string s)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("\"");
        foreach (char c in s)
        {
            switch (c)
            {
                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:
                    int i = (int)c;
                    if (i < 32 || i > 127)
                    {
                        sb.AppendFormat("\\u{0:X04}", i);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;
            }
        }
        sb.Append("\"");
     
        return sb.ToString();
    }

------解决方案--------------------
C# code

public static string Cleaner(string _s)
{
    if (_s == null) return "";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(_s);
    sb.Replace(@"\", @"\\");
    sb.Replace(@"'", @"\'");
    sb.Replace(@"""", @"\""");
    sb.Replace(Environment.NewLine, @"\n");    //替换连在一起的\r\n
    sb.Replace("\n", @"\n");                //单个替换
    sb.Replace("\r", @"\n");
    return sb.ToString();
}