Mirror site is read only www.netnr.com
netnr/ OfJson.cs 2018-09-26 13:03
JSON 字符串转义
/// <summary>
/// 字符串 JSON转义
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string OfJson(this string s)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.Length; i++)
    {
        char c = s.ToCharArray()[i];
        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();
}