Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double quotes in c# doesn't allow multiline

e.g.

string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";

I need to make it as for readability:

 string str = "
 {
   \"aps\":
         {
             \"alert\":\"" + title + "" + message + "\"
         }
 }";

How to achieve this, please suggest.

like image 835
Furqan Misarwala Avatar asked Jul 05 '17 05:07

Furqan Misarwala


2 Answers

If you really need to do this in a string literal, I'd use a verbatim string literal (the @ prefix). In verbatim string literals you need to use "" to represent a double quote. I'd suggest using interpolated string literals too, to make the embedding of title and message cleaner. That does mean you need to double the {{ and }} though. So you'd have:

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

Output:

{
   "aps":
   {
       "alert":"This is the title: (Message)"
   }
}

However, this is still more fragile than simply building up JSON using a JSON API - if the title or message contain quotes for example, you'll end up with invalid JSON. I'd just use Json.NET, for example:

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

That's much cleaner IMO, as well as being more robust.

like image 181
Jon Skeet Avatar answered Oct 20 '22 06:10

Jon Skeet


You could use what X-Tech has said, use additional concatenation operators ('+') on every line, or use the symbol '@':

 string str = @"
         {
           'aps':
                 {
                     'alert':'" + title + "" + message + @"'
                 }
         }";

Since its a JSON, you can use single quotes instead of double quotes.

About '@': Multiline String Literal in C#

like image 28
Arvind Sasikumar Avatar answered Oct 20 '22 06:10

Arvind Sasikumar