I'm having trouble using the System.Runtime.Serialization.Json.DataContractJsonSerializer
class to deserialize DateTime instances contained within a List<object>
. I cannot seem to get DateTime to deserialize back into the original type. The DataContractJsonSerializer
always deserializes it into a string type with the format "/Date(1329159196126-0500)/"
. It'll serialize and deserialize fine if I run it through using a strongly typed List<DateTime>
, however I am looking for way to get the serializer to identify and properly deserialize DateTimes when encountered within a simple list or array of object
.
Note that DateTimes are the only type besides primitives and strings that this list will ever contain. Here is the code snippet I'm using to test this.
var list = new List<object> { 27, "foo bar", 12.34m, true, DateTime.Now };
var serializer = new DataContractJsonSerializer(typeof (List<object>));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, list);
ms.Position = 0;
var deserializedList = serializer.ReadObject(ms) as List<object>;
}
In the .NET Framework version 4.5 the DataContractJsonSerializer
has a constructor that accepts a DataContractJsonSerializerSettings
object that can be used to set the DateTimeFormat
:
var ser = new DataContractJsonSerializer(typeof(CreateOmsEntryCommand),
new DataContractJsonSerializerSettings
{
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssZ")
});