json.net escaping of special characters

Tag: json.net Author: accp0915 Date: 2011-03-08

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?

Best Answer

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.

comments:

Thanks. Must have glanced over that paragraph. What would I need to do if I wanted to be strict about it and escape these characters (using json.net)?
@Steve: why would you want to do that? What advantage would you have?
we have an integration project that spans across multiple platforms (.NET on Win and Java on Unix). We log messages that come into various endpoints and are serializing the messages in JSON and logging them in the database. The Java apps are escaping everything, including ' and / and .NET apps are not. We are looking for consistency, that's all.
@Steve: since both formats are equivalent, you should be able to accept both. This means you need to parse the JSON correctly. If you do that, then it won't make a difference if it's escaped or not.
tell that to my colleague :). Thanks for your input, will go to the business and see what they have to say.