C# 如何转义JSON字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1242118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:06:18  来源:igfitidea点击:

How to escape JSON string?

c#jsonescaping

提问by theringostarrs

Are there any classes/functions available to be used for easy JSON escaping? I'd rather not have to write my own.

是否有任何类/函数可用于轻松转义 JSON?我宁愿不必自己写。

回答by Jim Schubert

There's a Json library at Codeplex

Codeplex有一个 Json 库

回答by Kevin Hakanson

I would also recommend using the JSON.NETlibrary mentioned, but if you have to escape unicode characters (e.g. \uXXXX format) in the resulting JSON string, you may have to do it yourself. Take a look at Converting Unicode strings to escaped ascii stringfor an example.

我还建议使用提到的JSON.NET库,但如果您必须在生成的 JSON 字符串中转义 unicode 字符(例如 \uXXXX 格式),您可能必须自己做。以将 Unicode 字符串转换为转义的 ascii 字符串为例。

回答by Clive Paterson

Yep, just add the following function to your Utils class or something:

是的,只需将以下函数添加到您的 Utils 类或其他东西:

    public static string cleanForJSON(string s)
    {
        if (s == null || s.Length == 0) {
            return "";
        }

        char         c = '
public static string EscapeStringValue(string value)
{
    const char BACK_SLASH = '\';
    const char SLASH = '/';
    const char DBL_QUOTE = '"';

    var output = new StringBuilder(value.Length);
    foreach (char c in value)
    {
        switch (c)
        {
            case SLASH:
                output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);
                break;

            case BACK_SLASH:
                output.AppendFormat("{0}{0}", BACK_SLASH);
                break;

            case DBL_QUOTE:
                output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE);
                break;

            default:
                output.Append(c);
                break;
        }
    }

    return output.ToString();
}
'; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); String t; for (i = 0; i < len; i += 1) { c = s[i]; switch (c) { case '\': case '"': sb.Append('\'); sb.Append(c); break; case '/': sb.Append('\'); sb.Append(c); break; case '\b': sb.Append("\b"); break; case '\t': sb.Append("\t"); break; case '\n': sb.Append("\n"); break; case '\f': sb.Append("\f"); break; case '\r': sb.Append("\r"); break; default: if (c < ' ') { t = "000" + String.Format("X", c); sb.Append("\u" + t.Substring(t.Length - 4)); } else { sb.Append(c); } break; } } return sb.ToString(); }

回答by Amit Bhagat

I have used following code to escape the string value for json. You need to add your '"' to the output of the following code:

我使用以下代码来转义 json 的字符串值。您需要将您的 '"' 添加到以下代码的输出中:

String.Format("X", c);

回答by user2058470

string t = ((int)c).ToString("X");

sb.Append("\u" + t.PadLeft(4, '0'));

That just outputs: X

那只是输出:X

Try this instead:

试试这个:

static string EscapeForJson(string s) {
  string quoted = System.Web.Helpers.Json.Encode(s);
  return quoted.Substring(1, quoted.Length - 2);
}

回答by Dejan

What about System.Web.Helpers.Json.Encode(...) (see http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx)?

System.Web.Helpers.Json.Encode(...) 怎么样(参见http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111) .aspx)?

回答by Rok Strni?a

Building on the answer by Dejan, what you can do is import System.Web.Helpers.NET Framework assembly, then use the following function:

基于Dejan 的回答,您可以做的是导入System.Web.Helpers.NET Framework 程序集,然后使用以下函数:

using Newtonsoft.Json;

....
var s = JsonConvert.ToString(@"a\b");
Console.WriteLine(s);
....

The Substringcall is required, since Encodeautomatically surrounds strings with double quotes.

Substring调用是必需的,因为Encode自动包围双引号的字符串。

回答by Dror Harari

For those using the very popular Json.Net project from Newtonsoft the task is trivial:

对于那些使用 Newtonsoft 非常流行的 Json.Net 项目的人来说,任务是微不足道的:

string quoted = HttpUtility.JavaScriptStringEncode(input);

This code prints:

此代码打印:

"a\\b"

“a\b”

That is, the resulting string value contains the quotes as well as the escaped backslash.

也就是说,结果字符串值包含引号以及转义的反斜杠。

回答by xmedeko

I use System.Web.HttpUtility.JavaScriptStringEncode

我用 System.Web.HttpUtility.JavaScriptStringEncode

Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms

\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms

回答by innominate227

I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's codewon by a good bit, presumably because the others are taking into account serialization options. Here are my results:

我对其中一些答案的长字符串和短字符串进行了速度测试。克莱夫帕特森的代码胜出不少,大概是因为其他人正在考虑序列化选项。这是我的结果:

public static void Main(string[] args)
{
    var testStr1 = "Apple Banana";
    var testStr2 = @"\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";

    foreach (var testStr in new[] { testStr1, testStr2 })
    {
        var results = new Dictionary<string,List<long>>();

        for (var n = 0; n < 10; n++)
        {
            var count = 1000 * 1000;

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
            }
            var t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.Helpers.Json.Encode(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = cleanForJSON(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Clive Paterson").Add(t);
        }

        Console.WriteLine(testStr);
        foreach (var result in results)
        {
            Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}

And here is the test code:

这是测试代码:

##代码##