博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

关于ASP.NET MVC 中JsonResult返回的日期值问题

Posted on 2017-06-23 11:09  冲杀  阅读(3239)  评论(0编辑  收藏  举报

最近开始用MVC做项目,在使用 JsonResult返回数据的时候,日期被反射成了/Date 1233455这种格式,遍查网上都是在客户端使用JS来处理这个问题的,这样的话,就需要在每一个涉及到日期的地方都做一次转换后,才能用来使用。

  于是我通过反编译Controller抽象类以及JsonResult类后发现:

  jsonresult中处理对象到JSON字符串的方法:

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
        }
        HttpResponseBase response = context.HttpContext.Response;
        if (!string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }
        if (this.Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            response.Write(serializer.Serialize(this.Data));
        }
    }

在这个方法里使用的是JavaScriptSerializer这个来序列化对象到JSON。

于是我自定义了一个类,继承JSONRESULT类

并将上面的方法从写 ,用newton.json替换javascriptSerializer

替换代码如下:

if (this.Data != null)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
        timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            response.Write(JsonConvert.SerializeObject(this.Data, Newtonsoft.Json.Formatting.Indented, timeFormat, x););
        }

这样处理了日期的JSON序列化。

然后再重新定义一个Controller,命名为 JsonController,且设置为抽象类。

然后重写方法:

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
}

将 JsonResult改为我们继承JSONResult并重写了ExecuteResult方法的类,就大工告成了!

 以后只要JsonResult涉及到返回日期的,就可以让控制器继承我们自定义的这个类,由此解决日期问题。

 

以上只解决了日期JSON后在JS中使用显示的问题,未解决日期参与运算的问题,但是根据我目前的经历,JS中日期参与预算的时间还比较少,所以能解决用于显示的问题,就很OK了,

ASP.NET MVC还有很多好玩的特性,大家一起摸索吧!