简体   繁体   English

将JSON日期/时间转换为C#日期时间

[英]Convert JSON Date/Time to C# DateTime

I have a DateTime that is being returned from a WCF webservice. 我有一个从WCF Web服务返回的DateTime。 this DateTime is part of a CLR object that has a DataContract attribute. 此DateTime是具有DataContract属性的CLR对象的一部分。 The DateTime is a property that has the DataMember attribute added to it. DateTime是添加了DataMember属性的属性。 Everything is returning properly to my client (a Silverlight application). 一切都正常返回给我的客户端(一个Silverlight应用程序)。

My question is, how do I take the serialized version of DateTime and convert it to a C# DateTime object? 我的问题是,如何获取DateTime的序列化版本并将其转换为C#DateTime对象?

Thank you! 谢谢!

The DateTime that gets returned from the web service will be in a weird format, like 从Web服务返回的DateTime将采用奇怪的格式,例如

\/Date(1297367252340-0500)\/

The reason the date is in this weird format is that DateTime is a primitive in WCF. 日期采用这种怪异格式的原因是DateTime是WCF中的原始类型。 Unfortunately, there is no universally standardized format for serializing dates and times in JSON -- various frameworks use various string formats. 不幸的是,没有用于序列化JSON中日期和时间的通用标准化格式-各种框架使用各种字符串格式。

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. 窘境是WCF需要本机理解导线上的特定字符串确实是DateTime,而不仅仅是另一个普通的JSON字符串。 Hence the strange format. 因此,奇怪的格式。 As soon as DataContractJsonSerializer encounters a date starting with /Date, it starts trying to parse it as a date. 一旦DataContractJsonSerializer遇到以/ 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. WCF客户端或Silverlight 2+客户端不应对此有问题-它们应使用System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject或System.Web.Script.Serialization.JavaScriptSerializer.Deserialize。

If you are using a web client, you can include the .js file that ships with ASP. 如果使用的是Web客户端,则可以包括ASP附带的.js文件。 NET AJAX (I believe it is called MicrosoftAspNetAjax.js, or MicrosoftAjax.cs, though the name may have changed). NET AJAX(尽管名称可能已更改,但我相信它称为MicrosoftAspNetAjax.js或MicrosoftAjax.cs)。 Its deserialize function will auto-parse these dates as well. 它的反序列化功能也会自动解析这些日期。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM