ASP.NET MVC 預設使用 JavaScriptSerializer 序列化日期時,會產生 /Date(1234567890)/ 這種難以閱讀的格式。解決方案是自訂 JsonResult 類別,在序列化輸出前透過正則表達式轉換為標準日期字串(如 yyyy-MM-dd HH:mm:ss)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
namespace App.Common {
public class ToJsonResult : JsonResult {
const string error = "該請求已被封鎖,因為敏感資訊洩露給第三方網站,這是 GET 請求時使用的。若要允許 GET 請求,請設定 JsonRequestBehavior AllowGet。";
public string FormateStr { get; set; }
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;
response.ContentType = String.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
if (Data != null) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonstring = serializer.Serialize(Data);
// 正則匹配 /Date(1234567890)/ 格式
string pattern = @"\/Date\(\d+\)\/";
MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(pattern);
jsonstring = reg.Replace(jsonstring, evaluator);
response.Write(jsonstring);
}
}
///
/// 將 JSON 序列化的時間轉為標準日期字串
///
private string ConvertJsonDateToDateString(Match m) {
StringBuilder sb = new StringBuilder();
Regex digitReg = new Regex(@"\d");
foreach (char c in m.Value) {
if (digitReg.IsMatch(c.ToString())) sb.Append(c);
}
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(sb.ToString()));
dt = dt.ToLocalTime();
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
}
}
在 Controller 中回傳 new ToJsonResult { Data = yourObject } 即可自動套用日期格式轉換,無需修改既有商業邏輯。