I have a DateTime that is being returned from a WCF webservice. this DateTime is part of a CLR object that has a DataContract attribute. The DateTime is a property that has the Data开发者_StackOverflow中文版Member attribute added to it. Everything is returning properly to my client (a Silverlight application).
My question is, how do I take the serialized version of DateTime and convert it to a C# DateTime object?
Thank you!
The DateTime that gets returned from the web service will be in a weird format, like
\/Date(1297367252340-0500)\/
The reason the date is in this weird format is that DateTime is a primitive in WCF. Unfortunately, there is no universally standardized format for serializing dates and times in JSON -- various frameworks use various string formats.
The dilemma is that WCF needs to natively understand that a particular string over the wire is indeed a DateTime, not just another plain vanilla JSON string. Hence the strange format. As soon as DataContractJsonSerializer encounters a date starting with /Date, it starts trying to parse it as a date.
A WCF client or a Silverlight 2+ client should NOT have problems with this -- they should use System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject or System.Web.Script.Serialization.JavaScriptSerializer.Deserialize.
If you are using a web client, you can include the .js file that ships with ASP. NET AJAX (I believe it is called MicrosoftAspNetAjax.js, or MicrosoftAjax.cs, though the name may have changed). Its deserialize function will auto-parse these dates as well.
Hope that helps!
精彩评论