c#中的双引号不允许多行

Fur*_*ala 4 c# json c#-3.0 c#-4.0

例如

string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";
Run Code Online (Sandbox Code Playgroud)

我需要把它作为可读性:

 string str = "
 {
   \"aps\":
         {
             \"alert\":\"" + title + "" + message + "\"
         }
 }";
Run Code Online (Sandbox Code Playgroud)

如何实现这一点,请建议.

Jon*_*eet 17

如果你真的需要在字符串文字中这样做,我会使用逐字字符串文字(@前缀).在逐字字符串文字中,您需要使用它""来表示双引号.我建议也使用插值字符串文字来嵌入titlemessage清理.这确实意味着你需要加倍{{并且}}尽管如此.所以你有:

string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
   ""aps"":
   {{
       ""alert"":""{title}{message}""
   }}
}}";
Console.WriteLine(str);
Run Code Online (Sandbox Code Playgroud)

输出:

{
   "aps":
   {
       "alert":"This is the title: (Message)"
   }
}
Run Code Online (Sandbox Code Playgroud)

但是,这仍然比使用JSON API简单地构建JSON更脆弱 - 例如,如果标题或消息包含引号,则最终会得到无效的JSON.我只是使用Json.NET,例如:

string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
    ["aps"] = new JObject 
    { 
        ["alert"] = title + message 
    }
};
Console.WriteLine(json.ToString());
Run Code Online (Sandbox Code Playgroud)

这是清洁的IMO,同时也更加强大.