Language: C#
DataContract Serializer and ISO dates not working - feature request
[TestClass] public class DateConversionTests { public DateConversionTests() { } [TestMethod] public void AjaxDate_IsoDate_DataContract_DeserializationTest() { string isodate = "\"2009-09-14T08:22:11Z\""; // fails - IDEALLY this should work to work with native JSON parsers DateTime date = (DateTime)FromJsonString(isodate, typeof(DateTime)); Console.WriteLine(date); } [TestMethod] public void AjaxDate_IsoDate_JavaScriptSerializer_DeserializationTest() { string isodate = "\"2009-09-14T08:22:11Z\""; JavaScriptSerializer ser = new JavaScriptSerializer(); // works fine DateTime date = ser.Deserialize<DateTime>(isodate); Console.WriteLine(date); } [TestMethod] public void AjaxDate_MsDate_DataContract_DeserializationTest() { string msajaxdate = "\"\\/Date(1252969200000-0700)\\/\""; // works - full MS Ajax Date DateTime date = (DateTime) FromJsonString(msajaxdate, typeof(DateTime)); Console.WriteLine(date); } [TestMethod] public void AjaxDate_MsDate_Simplified_DataContract_DeserializationTest() { string msajaxdate = "\"/Date(1252969200000-0700)/\""; // Also works - surprisingly as it's effectively a complete different format DateTime date = (DateTime)FromJsonString(msajaxdate, typeof(DateTime)); Console.WriteLine(date); } [TestMethod] public void AjaxDate_MsDate_Simplified_JavaScriptSerializer_DeserializationTest() { string msajaxdate = "\"/Date(1252969200000-0700)/\""; JavaScriptSerializer ser = new JavaScriptSerializer(); // doesn't work DateTime date = ser.Deserialize<DateTime>(msajaxdate); Console.WriteLine(date); } static object FromJsonString(string json, Type type) { MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer ser = new DataContractJsonSerializer(type); object value = ser.ReadObject(ms); ms.Close(); return value; } /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } }
Tags:
Description:
Demonstrates that the DataContractSerializer doesn't serialize JSON ISO dates while the JavaScriptSerializer does.
The end result of this shortcoming is that you can't use the native JSON parsers in browsers with WCF directly. Even a Replacer won't do the trick because Replacer results are encoded and the \/Date()\/ syntax can't be created from an encoded string.
The end result of this shortcoming is that you can't use the native JSON parsers in browsers with WCF directly. Even a Replacer won't do the trick because Replacer results are encoded and the \/Date()\/ syntax can't be created from an encoded string.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

