At the moment, my team and I are working on an ASP.NET project that requires some significant user interaction and data exchange. We chose to standardize the data exchange format on JSON. The primary reason for this is to allow us to serialize business entity objects and exchange them between the client and server in identical structure. This allows us to utilize the entities on the client side, have the user operate on the data and then send the serialized entities back to the server to be recreated as .NET objects. Hopefully the benefits of this are apparent, if not well, that’s topic for another time.
In addition, we have a WCF service that utilizes the entities as well. As a result, the entity classes are decorated with the DataContract attribute instead of the Serializable attribute. Since this is the approach we took with serialization, it led us to use the DataContractJsonSerializer for serializing to JSON. There is a wonderful article that includes a class that uses generics to serialize .NET objects, and it can be found here. Excellent information to be found there.
The details of how to serialize an object to JSON is covered elsewhere in detail. What I wanted to cover here is a “gotcha” when your entity contains a DateTime field. When you serialize a DateTime to JSON with the DataContractJsonSerializer, you get the following format (assuming the field name is “Created”;
“{\”Created\”:\”\\/Date(1232739449000-0500)\\/\”}”
The \/Date()\/ is a Microsoft work around to an issue with dates and JavaScript, you can find a discussion on this here if you’re interested. This is the seed of the “gotcha” due to the escape characters. However, it’s only a gotcha when you send the string back to the server. When you serialize a JavaScript Date using Sys.Serialization.JavaScriptSerializer object, you get the following string on the client side;
“{\”Created\”:\”\\\”\\\\/Date(1233698640637)\\\\/\\\”\”}”
The extra escape characters cause problems when the DataContractJsonSerializer encounters it and tries to create a DateTime from the value. The value is interpreted as a string, and not a date value. What we had to do was scrub the JSON text passed in to the server method to remove the extra escape characters. Using the Replace() method on the String replace “\\\”\\\\/D” with “\”\\\\/D” at the prefix and replace “)\\\\/\\\”” with “)\\\\/” on the suffix. So far this seems to work and after executing these two replace calls, we get the following;
“{\”Created\”:\”\\/Date(1233698977441)\\/\”}”
Now that looks remarkably similar to the initial serialization result. And when calling the deserialize method, we get our .NET entity object with all the values correctly set.


Recent Comments