1. 程式人生 > >mvc 返回json格式時間格式化

mvc 返回json格式時間格式化

 protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new ToJsonResult
            {
                Data = data,
                ContentEncoding = contentEncoding,
                ContentType 
= contentType, JsonRequestBehavior = behavior, FormateStr = "yyyy-MM-dd HH:mm:ss" }; } protected JsonResult MyJson(object data) { return new ToJsonResult { Data = data, FormateStr
= "yyyy-MM-dd" }; }
 /// <summary>
    /// 說明:轉化為Jason
    /// 作者: CallmeYhz
    /// </summary>
    public class ToJsonResult : JsonResult
    {
        const string error = "該請求已被封鎖,因為敏感資訊透露給第三方網站,這是一個GET請求時使用的。為了可以GET請求,請設定JsonRequestBehavior AllowGet。";
        /// <summary>
/// 格式化字串 /// </summary> public string FormateStr { get; set; } /// <summary> /// 說明:重寫ExecueResult方法 /// 作者:CallmeYhz /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(error); } HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonstring = serializer.Serialize(Data); //string hashOldPassword = @"\\/Date\((\param+)\+\param+\)\\/"; string p = @"\\/Date\(\d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonstring = reg.Replace(jsonstring, matchEvaluator); response.Write(jsonstring); } } /// <summary> /// 說明:將Json序列化的時間由/Date(1294499956278+0800)轉為字串 /// 作者:CallmeYhz /// </summary> private string ConvertJsonDateToDateString(Match m) { string result = string.Empty; string p = @"\d"; var cArray = m.Value.ToCharArray(); StringBuilder sb = new StringBuilder(); Regex reg = new Regex(p); for (int i = 0; i < cArray.Length; i++) { if (reg.IsMatch(cArray[i].ToString())) { sb.Append(cArray[i]); } } // reg.Replace(m.Value; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(sb.ToString())); dt = dt.ToLocalTime(); result = dt.ToString(this.FormateStr); return result; } }

將此程式碼新增到baseControle 中就可以了