11

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.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
Furqan Misarwala
  • 1,413
  • 4
  • 21
  • 46

2 Answers2

37

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.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • @furqanms: Sorry, I don't know what you mean. The code I've given doesn't produce any extra braces, and it's unclear what code you're using. – Jon Skeet Jul 05 '17 at 06:44
  • Sorry, It was my mistake, JObject is great for readability, Thanks @Jon Skeet – Furqan Misarwala Jul 05 '17 at 06:47
  • Your Json.NET for me is the correct answer, it worked for me and got me out of a hole during development of an app too so thanks for sharing – System24 Tech Jan 17 '18 at 08:49
3

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#

Arvind Sasikumar
  • 402
  • 3
  • 12