如何在代码中编写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}"; 

..但它显示错误..

你必须这样做

 String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}"; 

请参阅此内容以供参考
也来自msdn 🙂

 Short Notation UTF-16 character Description \' \u0027 allow to enter a ' in a character literal, eg '\'' \" \u0022 allow to enter a " in a string literal, eg "this is the double quote (\") character" \\ \u005c allow to enter a \ character in a character or string literal, eg '\\' 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,然后进行序列化。

https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/

 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); 

你必须像这样转义字符串中的引号:

 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}";