1、先新建一个 JsonConvertResult:JsonResult,继承自JsonResult;
public class JsonConvertResult : JsonResult { ////// 格式化字符串 /// public string FormateStr { get; set; } ////// 重写执行视图 /// /// 上下文 public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; //response.setContentType("text/html;charset=utf-8"); } if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data != null) { JavaScriptSerializer jss = new JavaScriptSerializer(); string jsonString = jss.Serialize(Data); string p = @"\\/Date\((\d+)\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); JsonSerializerSettings set = new JsonSerializerSettings(); set.NullValueHandling = NullValueHandling.Ignore; //string jsonString = ExtJsonManager.SerializeObject(Data); response.Write(jsonString); } } ////// 将Json序列化的时间由/Date(1294499956278)转为字符串 . /// /// 正则匹配 ///格式化后的字符串 private string ConvertJsonDateToDateString(Match m) { string result = string.Empty; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); result = dt.ToString(FormateStr); return result; } }
2、BaseController中重写Json返回值方法就可以了。
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) { return new JsonConvertResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, FormateStr = "yyyy-MM-dd HH:mm:ss" }; }