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 aDataContractJsonSerializerSettings
object that can be used to set theDateTimeFormat
:You could convert DateTime.Now to a string before serialization and
convert it back to DateTime after deserialization.
Conversion to string by:
Conversion back to DateTime after deserialization:
So the whole code would be like:
If
DataContractJsonSerializer
isn't a must, here is a solution using Json.Net.This is the Json string
and returned types are
long
,string
,double
,bool
andDateTime
This seems like very strange behavior, my guess is that it stems from DateTime not being a type that is recongnized in JSON. However, you can roll your own IDataContractSurrogate to modify the serialization/deserialization process.
To use this modify your sample code when you create the the serializer to this:
Then add this class: