Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

c# - DataContractJsonSerializer - Deserializing DateTime within List<object>

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>;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")
              });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...