Parsing a JSON date info into a C# DateTime

前端 未结 4 1904
小鲜肉
小鲜肉 2021-01-11 19:11

I have a a WCF service that returns a CLR object. This object is defined as follows:

[DataContract]
public class Person
{
  [DataMember]
  public string Full         


        
4条回答
  •  借酒劲吻你
    2021-01-11 19:24

    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.

    Now, to answer your question, when you are sending a DateTime over the wire, it depends on if you're using a web browser client, a Silverlight client, or a WCF client.

    A WCF client or a Silverlight 2+ client should NOT have problems with this -- they should auto-use the DataContractJsoNSerializer, and if they're not using it, you can plug in DCJS manually.

    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!

提交回复
热议问题