我想将以下字符串存储在 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}";
..但它显示错误..
你必须这样做
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
我更喜欢这个,只要确保字符串中没有单引号
string str = "{'Id':'123','DateOfRegistration':'2012 - 10 - 21T00: 00:00 + 05:30','Status':0}"
.Replace("'", "\"");
有另一种方法可以使用 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);
微调sudhAnsu63 的答案,这是一个单行:
使用.NET 核心:
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
.
您必须像这样转义字符串中的引号:
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}";
使用 Verbatim String Literals ( @"..."
) 您可以通过用双引号对交换双引号来编写内联多行 json - "" 而不是 "。示例:
string str = @"
{
""Id"": ""123"",
""DateOfRegistration"": ""2012-10-21T00:00:00+05:30"",
""Status"": 0
}";
对于一个开箱即用的解决方案,我将 JSON 编码为 base64,以便可以将其作为字符串值导入一行。
这可以保留行格式,而无需手动编写动态对象或转义字符。格式与从文本文件中读取 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);