Data Analysis DataContractJsonSerializer iso 8601 date

I have json that has a date like 2012-06-07T00:29:47.000 and needs to be deserialized. But on

  DataContractJsonSerializer serializer = new DataContractJsonSerializer(type); return (object)serializer.ReadObject(Util.GetMemoryStreamFromString(json)); 

I get below exception

 There was an error deserializing the object of type System.Collections.Generic.List`1 [[MyNameSpace.MyClass, MyNameSpace, Version=1.0.4541.23433, Culture=neutral, PublicKeyToken=null]]. DateTime content '2012-06-07T00:29:47.000' does not start with '\/Date(' and end with ')\/' as required for JSON 

It works on Windows Mobile 7 but the same code does not work on Windows 8.
The expected date format is \/Date(1337020200000+0530)\/ instead of 2012-06-07T00:29:47.000 .

Is custom serialization required, if so, how? And I can not use JSON.NET I must use DataContractJsonSerializer , and I can not change the JSON format, since the same JSON is used for android.
I am new to .net. Thanks.

+6
source share
1 answer

Use one string property for serialization / deserialization and a separate non-serialized property that converts it to DateTime. It’s easier to see a sample code:

 [DataContract] public class LibraryBook { [DataMember(Name = "ReturnDate")] // This can be private because it only ever accessed by the serialiser. private string FormattedReturnDate { get; set; } // This attribute prevents the ReturnDate property from being serialised. [IgnoreDataMember] // This property is used by your code. public DateTime ReturnDate { // Replace "o" with whichever DateTime format specifier you need. // "o" gives you a round-trippable format which is ISO-8601-compatible. get { return DateTime.ParseExact(FormattedReturnDate, "o", CultureInfo.InvariantCulture); } set { FormattedReturnDate = value.ToString("o"); } } } 

Instead, you can parse a FormatterReturnDate so that it can fail earlier if a bad date is received.


Edited to include GôTô to give the serial name DataMember the correct name.

+7
source

Source: https://habr.com/ru/post/917606/


All Articles