最近開始用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還有很多好玩的特性,大家一起摸索吧!