我想将以下字符串存储在字符串变量中
{"Id":"123","注册日期":"2012-10-21T00:00:00+05:30","状态":0}
这是我使用的代码..
String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}";
..但显示错误..
你必须这样做
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
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
C# 10 及更低版本
我更喜欢这个;只需确保字符串中没有单引号。
var str = "{'Id':'123','DateOfRegistration':'2012-10-21T00:00:00+05:30','Status':0}"
.Replace("'", "\"");
C# 11 及以上
您可以简单地将 json 放在一对三重双引号内:“””
var str = """
{
"Id": "123",
"DateOfRegistration": "2012-10-21T00:00:00+05:30",
"Status": 0
}
""";
微调sudhAnsu63的答案,这是一个one-liner:
使用 .NET Core:
string str = JsonSerializer.Serialize(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
与Json.NET:
string str = JsonConvert.SerializeObject(
new {
Id = 2,
DateOfRegistration = "2012-10-21T00:00:00+05:30",
Status = 0
}
);
不需要实例化一个
dynamic ExpandoObject
。
还有另一种方法可以使用 Expando 对象或 XElement 编写这些复杂的 JSON,然后进行序列化。
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);
使用逐字字符串文字 (
@"..."
),您可以通过将双引号与双引号对交换来编写内联多行 json - "" 而不是 "。示例:
string str = @"
{
""Id"": ""123"",
""DateOfRegistration"": ""2012-10-21T00:00:00+05:30"",
""Status"": 0
}";
您必须像这样转义字符串中的引号:
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
C# 11 引入了一项名为“原始字符串文字”的新功能。它使得使用 JSON 变得非常容易。只需使用三个双引号字符 ("""
) 作为标记来将字符串括起来即可:
string str = """{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}""";
Nick Chapsas 的相关 YouTube 视频:C# 11 中的字符串变得更好了
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
这会保留行格式,而无需手动编写动态对象或转义字符。格式与从文本文件读取 JSON 相同:
var base64 = "eyJJZCI6IjEyMyIsIkRhdGVPZlJlZ2lzdHJhdGlvbiI6IjIwMTItMTAtMjFUMDA6MDA6MDArMDU6MzAiLCJTdGF0dXMiOjB9";
byte[] data = Convert.FromBase64String(base64);
string json = Encoding.UTF8.GetString(data);
//using the JSON text
var result = JsonConvert.DeserializeObject<object>(json);