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.
See more on this question at Stackoverflow