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.
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.
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#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With