using System; using System.Configuration; using System.Text.RegularExpressions; using System.Web; using System.Web.Configuration; using System.Web.Mvc; using System.Web.Script.Serialization; namespace WX.CRM.WebHelper { public class JsonHelper { public static T JsonDivertToObj(string json) { JavaScriptSerializer script = new JavaScriptSerializer(); T dic = script.Deserialize(json); return dic; } public static string ObjDivertToJson(object obj) { ScriptingJsonSerializationSection section = ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as ScriptingJsonSerializationSection; JavaScriptSerializer script = new JavaScriptSerializer(); script.MaxJsonLength = section != null ? section.MaxJsonLength : int.MaxValue; string json = script.Serialize(obj); return json; } } public class ConfigurableJsonResult : JsonResult { 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("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } 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(); ScriptingJsonSerializationSection section = ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as ScriptingJsonSerializationSection; if (section != null) { serializer.MaxJsonLength = section.MaxJsonLength; serializer.RecursionLimit = section.RecursionLimit; } else { serializer.MaxJsonLength = int.MaxValue; } var str = serializer.Serialize(Data); str = Regex.Replace(str, @"\\/Date\((\d+)\)\\/", match => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); }); response.Write(str); } } } }