一、Json. Net(newtons)和 ASP. net MVc的结合
1. Json. Net的介绍:ASP. Net mvc默认是使用 JavaScriptSerializer做json序列化,但是该方法好多的弊端,并且不好用,例如:( Date Time
日期的格式化、循环引用、属性名开头小写等)。而 Json. Net( newtonjs)很好的解决了这些问题,是Net中使用频率非常高的json库。
2. json.net的安装:nuget下载安装Newtonsoft.Json。
3. 第一种使用json.net 的方式:首先需要重新json.net 方法,添加类如下
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication { public class JsonNetResult : JsonResult { public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore,//忽略循环引用,如果设置为Error,则遇到循环引用的时候报错(建议设置为Error,这样更规范) DateFormatString = "yyyy-MM-dd HH:mm:ss",//日期格式化,默认的格式也不好看 ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()//json中属性开头字母小写的驼峰命名 }; } public JsonSerializerSettings Settings { get; private set; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("JSON GET is not allowed"); HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) response.ContentEncoding = this.ContentEncoding; if (this.Data == null) return; var scriptSerializer = JsonSerializer.Create(this.Settings); scriptSerializer.Serialize(response.Output, this.Data); } } }
调用如下:
return new JsonNetResult() { Data=结果值};
4. 第二种使用AOP思想完成的方式:使用该方式对系统的侵入式会达到最低。只需要执行如下两步操作:
4.1 新建一个过滤器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication { public class JsonNetActionFilter : IActionFilter { public void OnActionExecuted(ActionExecutedContext filterContext) { //把 filterContext.Result从JsonResult换成JsonNetResult //filterContext.Result值得就是Action执行返回的ActionResult对象 if (filterContext.Result is JsonResult &&!(filterContext.Result is JsonNetResult)) { JsonResult jsonResult = (JsonResult)filterContext.Result; JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.ContentEncoding = jsonResult.ContentEncoding; jsonNetResult.ContentType = jsonResult.ContentType; jsonNetResult.Data = jsonResult.Data; jsonNetResult.JsonRequestBehavior = jsonResult.JsonRequestBehavior; jsonNetResult.MaxJsonLength = jsonResult.MaxJsonLength; jsonNetResult.RecursionLimit = jsonResult.RecursionLimit; filterContext.Result = jsonNetResult; } } public void OnActionExecuting(ActionExecutingContext filterContext) { } } }
4.2 在global文件中添加全局过滤器
GlobalFilters.Filters.Add(new JsonNetActionFilter());
4.3 在ActionResult方法中依旧还是原来的用法返回
return Json()