use*_*801 18 c# string syntax json
我想将以下字符串存储在String变量中
{ "ID": "123", "DateOfRegistration": "2012-10-21T00:00:00 + 05:30", "状态":0}
这是我使用的代码..
String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}";
Run Code Online (Sandbox Code Playgroud)
..但它显示错误..
Fre*_*eak 33
你必须这样做
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
mró*_*ówa 14
使用 Verbatim String Literals ( @"..."
),您可以通过将双引号与双引号对交换来编写内联多行 json - "" 而不是 "。示例:
string str = @"
{
""Id"": ""123"",
""DateOfRegistration"": ""2012-10-21T00:00:00+05:30"",
""Status"": 0
}";
Run Code Online (Sandbox Code Playgroud)
Moh*_*van 10
我更喜欢这个,只要确保你的字符串中没有单引号
string str = "{'Id':'123','DateOfRegistration':'2012 - 10 - 21T00: 00:00 + 05:30','Status':0}".Replace("'", "\"");
Run Code Online (Sandbox Code Playgroud)
微调@sudhAnsu63 回答这是一个单行:
使用NET 核心
string str = JsonSerializer.Serialize(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
Run Code Online (Sandbox Code Playgroud)
与Json.Net
string str = JsonConvert.SerializeObject(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
Run Code Online (Sandbox Code Playgroud)
有没有必要实例化dynamic ExpandoObject
。
C# 11 引入了一项名为原始字符串文字的新功能。它使得使用 JSON 变得非常容易。只需使用三个双引号字符 ( """
) 作为标记而不是使用一个双引号字符 ( ) 将字符串括起来:
string str = """{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}""";
Run Code Online (Sandbox Code Playgroud)
Nick Chapsas 的相关 YouTube 视频:C# 11 中的字符串变得更好了。
还有一种替代方法,可以使用Expando对象或XElement编写这些复杂的JSON,然后进行序列化。
dynamic contact = new ExpandoObject();
contact.Name = “Patrick Hines”;
contact.Phone = “206-555-0144”;
contact.Address = new ExpandoObject();
contact.Address.Street = “123 Main St”;
contact.Address.City = “Mercer Island”;
contact.Address.State = “WA”;
contact.Address.Postal = “68402”;
//Serialize to get Json string using NewtonSoft.JSON
string Json = JsonConvert.SerializeObject(contact);
Run Code Online (Sandbox Code Playgroud)
您必须这样对字符串中的引号进行转义:
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
Run Code Online (Sandbox Code Playgroud)