mvc 使用json.net 替换JsonResult 默认序列化
默认mvc json序列化 机制处理日期等字段时 格式并不是我们想要的格式
我们可以使用json.net 覆盖mvc默认的序列化行为
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Web; 8 using System.Web.Mvc; 9 using Newtonsoft.Json; 10 11 namespace Ecomm.Common.Web.Result 12 { 13 /// <summary> 14 /// 覆盖默认 JsonResult 中JavascriptSerializer 序列化json 改用 json.net 序列化对象。处理日期问题 15 /// </summary> 16 public class JsonNetResult : JsonResult 17 { 18 public JsonNetResult() 19 { 20 Settings = new JsonSerializerSettings 21 { 22 ReferenceLoopHandling = ReferenceLoopHandling.Error 23 }; 24 } 25 26 public JsonSerializerSettings Settings { get; private set; } 27 28 public override void ExecuteResult(ControllerContext context) 29 { 30 if (context == null) 31 throw new ArgumentNullException("context"); 32 if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 33 throw new InvalidOperationException("JSON GET is not allowed"); 34 35 HttpResponseBase response = context.HttpContext.Response; 36 response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; 37 38 if (this.ContentEncoding != null) 39 response.ContentEncoding = this.ContentEncoding; 40 if (this.Data == null) 41 return; 42 43 var scriptSerializer = JsonSerializer.Create(this.Settings); 44 45 using (var sw = new StringWriter()) 46 { 47 scriptSerializer.Serialize(sw, this.Data); 48 response.Write(sw.ToString()); 49 } 50 } 51 } 52 }
可以在baseController中覆盖默认 序列化行为
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Web; 7 using System.Web.Mvc; 8 using System.Data; 9 using Newtonsoft.Json; 10 11 namespace Ecomm.Mvc.Web.Controllers 12 { 13 public class BaseController:Controller 14 { 15 // 16 // GET: /Base/ 17 // 项目都继承 Base 以后可以在这里扩展统一方法 18 19 /// <summary> 20 /// 覆盖重载默认的 JsonResult 序列化json 逻辑 改用json.net 引擎序列化对象 21 /// 解决 日期格式等问题 22 /// </summary> 23 /// <param name="data"></param> 24 /// <param name="contentType"></param> 25 /// <param name="contentEncoding"></param> 26 /// <param name="behavior"></param> 27 /// <returns></returns> 28 protected override JsonResult Json(object data, string contentType, 29 Encoding contentEncoding, JsonRequestBehavior behavior) 30 { 31 return new JsonNetResult 32 { 33 Data = data, 34 ContentType = contentType, 35 ContentEncoding = contentEncoding, 36 JsonRequestBehavior = behavior 37 }; 38 } 39 /// <summary> 40 /// controller action 执行之前执行 41 /// </summary> 42 /// <param name="filterContext"></param> 43 protected override void OnActionExecuting(ActionExecutingContext 44 filterContext) 45 { 46 //todo 在默认action 被执行前可以做的事情... 47 48 } 49 } 50 }
也可以在JsonResult 中手动调用
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。