Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net escaping of special characters

Tags:

json.net

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?

like image 551
stephenl Avatar asked Oct 24 '25 05:10

stephenl


1 Answers

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.

like image 54
Joachim Sauer Avatar answered Oct 27 '25 01:10

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!