How to write JSON string value in code?
C# 10 and lower
I prefer this; just make sure you don't have a single quote in the string.
var str = "{'Id':'123','DateOfRegistration':'2012-10-21T00:00:00+05:30','Status':0}"
.Replace("'", "\"");
C# 11 and upper
It is still in preview mode, but you can simply place your json inside a pair of triple double-quote: """
var str = """
{
"Id": "123",
"DateOfRegistration": "2012-10-21T00:00:00+05:30",
"Status": 0
}
""";
You have to do this
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
Please see this for reference
Also from msdn :)
Short Notation UTF-16 character Description
\' \u0027 allow to enter a ' in a character literal, e.g. '\''
\" \u0022 allow to enter a " in a string literal, e.g. "this is the double quote (\") character"
\\ \u005c allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character"
\0 \u0000 allow to enter the character with code 0
\a \u0007 alarm (usually the HW beep)
\b \u0008 back-space
\f \u000c form-feed (next page)
\n \u000a line-feed (next line)
\r \u000d carriage-return (move to the beginning of the line)
\t \u0009 (horizontal-) tab
\v \u000b vertical-tab
There is an alternate way to write these complex JSON using Expando object or XElement and then serialize.
https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/
dynamic contact = new ExpandoObject
{
Name = "Patrick Hines",
Phone = "206-555-0144",
Address = new ExpandoObject
{
Street = "123 Main St",
City = "Mercer Island",
State = "WA",
Postal = "68402"
}
};
//Serialize to get Json string using NewtonSoft.JSON
string Json = JsonConvert.SerializeObject(contact);
Finetuning on sudhAnsu63's answer, this is a one-liner:
With .NET Core:
string str = JsonSerializer.Serialize(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
With Json.NET:
string str = JsonConvert.SerializeObject(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
There is no need to instantiate a dynamic ExpandoObject
.