asp.net-mvc-2 – JavaScriptSerializer没有正确反序列化DateTime / TimeSpan

一个问题,其中DateTime / TimeSpan似乎没有使用JavaScriptSerializer正确反序列化.
当我在反序列化后得到Object时,TimeSpan为空,如果我使用DateTime,那么时间就完全没了.
找到了这篇文章,但它并没有真正帮助我太多.
http://www.west-wind.com/weblog/ShowPost.aspx?id=471402

有人有主意吗?我应该尝试json.net库吗?

public class JsonFilter : ActionFilterattribute
{
    public string Param { get; set; }
    public Type JsonDataType { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
        {
            string inputContent;
            using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
            {
                inputContent = sr.ReadToEnd();
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var result = serializer.Deserialize(inputContent,JsonDataType);
            filterContext.ActionParameters[Param] = result;
        }
    }
}

public class RosterItem
{
    public RosterItem()
    {
        comments = new List<Form.Comment>();
    }
    public Boolean dirty { get; set; }
    public int id { get; set; }
    public int staffId { get; set; }
    public String description { get; set; }
    public int activityId { get; set; }
    public DateTime date { get; set; }
    public TimeSpan startTime { get; set; }
    public TimeSpan endTime { get; set; }
    public List<Form.Comment> comments { get; set; }
}

    [JsonFilter(Param = "rosterItem",JsonDataType = typeof(RosterItem))]
    public int SaveRosterEntry(RosterItem rosterItem)
    {
        RosterEntry rosterEntry = rosterEntryRepository.GetRosterEntry(rosterItem.id);
        if (rosterEntry == null)
        {
            rosterEntry = new RosterEntry();
            rosterEntryRepository.Add(rosterEntry);
        }
        rosterEntry.ActivityID = rosterItem.activityId;
        rosterEntry.StartTime = rosterItem.startTime;
        rosterEntry.EndTime = rosterItem.endTime;
        rosterEntry.RosterDate = rosterItem.date;
        rosterEntry.RosterEmployeeID = rosterItem.staffId;            
        rosterEntryRepository.Save();
        return rosterEntry.RosterEntryID;
    }

解决方法

我在GitHub上的帖子中找到了答案:

https://github.com/NancyFx/Nancy/issues/336

基本上答案是创建一个新的TimeSpanjsonConverter,它继承自JavaScriptConverter,然后将其传递给序列化程序类的实例:

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer()
serializer.RegisterConverters(new[] { new TimeSpanjsonConverter() });

全班供参考(由GrumpyDev编写):

public class TimeSpanjsonConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new[] { typeof(TimeSpan) };
        }
    }

    public override object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer)
    {
        return new TimeSpan(
            this.GetValue(dictionary,"days"),this.GetValue(dictionary,"hours"),"minutes"),"seconds"),"milliseconds"));
    }

    public override IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer)
    {
        var timeSpan = (TimeSpan)obj;

        var result = new Dictionary<string,object>
            {
                { "days",timeSpan.Days },{ "hours",timeSpan.Hours },{ "minutes",timeSpan.Minutes },{ "seconds",timeSpan.Seconds },{ "milliseconds",timeSpan.Milliseconds }
            };

        return result;
    }

    private int GetValue(IDictionary<string,string key)
    {
        const int DefaultValue = 0;

        object value;
        if (!dictionary.TryGetValue(key,out value))
        {
            return DefaultValue;
        }

        if (value is int)
        {
            return (int)value;
        }

        var valueString = value as string;
        if (valueString == null)
        {
            return DefaultValue;
        }

        int returnValue;
        return !int.TryParse(valueString,out returnValue) ? DefaultValue : returnValue;
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....