json.net escaping of special characters

巧了我就是萌 提交于 2019-12-10 20:42:31

问题


Bit new to JSON so please excuse the simpleton question, but according to the list of special characters found here and here, single quote (') characters are meant to be escaped. The specification also treats solidus (/) as escapable character. To illustrate I'm using the documentation example (slightly modified).

input:

Product product = new Product();

product.Name = "O'Grady's Apples";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large", "X/Large" };

output = JsonConvert.SerializeObject(product, Formatting.Indented);

output:

{    
"Name": "O'Grady's Apples",  
"Expiry": "\/Date(1230422400000+0000)\/",
"Price": 3.99,
"Sizes": ["Small","Medium","Large", "X/Large"]
}

What I would expect to see is

{  
"Name": "O\'Grady\'s Apples",...  
"Sizes": ["Small","Medium","Large", "X\/Large"]  
}

Is this intended? Or am I misinterpreting the specifications?


回答1:


While everything can be escaped inside a string, only a very limited set needs to be escaped:

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

So only ", \ and the unprintable control characters must be escaped.



来源:https://stackoverflow.com/questions/5417344/json-net-escaping-of-special-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!