使用Newtonsoft.Json 解决Json日期格式问题

介绍

Asp.Net MVC默认是使用JavaScriptSerializer做Json序列化的,不好用。而且JavaScriptSerializer无法处理循环引用,对日期的格式化不友好。例如对当前日期序列化后的效果是这样的:【CreateTime:"/Date(1521983727837)/"】 这样的日期我们很难看懂

而且JavaScriptSerializer对一个对象的序列化,序列化后的json对象属性与C#中的对象的属性名称一致。因为我们在javascript中习惯将对象属性的第一个字母是以小写开头的,不习惯属性的第一个字母是大写开头的,比如:,比如 id,name,createTime
而在C#中,我们对象的属性名称习惯是以大些字母开头,比如Id,Name,CreateTime

如果使用JavaScriptSerializer对C#对象进行序列化,序列化后的属性名称与c#定义的属性名称一致,无法将对象第一个字母变为小写的字母,这样对前端的开发人员就不太友好(前端开发人员会觉得这样的属性名称很恶心) 那有什么办法解决这个问题呢? 这里我们就得说说这个Newtonsoft.Json了

举列:

  1. public class Person
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public DateTime CreateTime { get; set; }
  6. }

如果使用JavaScriptSerializer对这个对象序列化,序列化后的效果是这样的:

  1. {Id: 1,Name: "张三",CreateTime: "/Date(1521983727837)/"}

那什么现在使用newtonjs 对这个对象进行序列化就能达到我们想要的效果

  1. {id: 1,name: "张三",createTime: "2018-03-25 22:26:07"}

 

那现在什么来看看那这个Newtonsoft.Json怎么用

第一步:首先去Nuget中 安装Newtonsoft.Json 版本是11.0.2

或者执行PM>Install-Package Newtonsoft.Json -Version 11.0.2

第二步: 新建一个JsonNetResult类 让这个类继承JsonResult类

  1. namespace MvcApp.Controllers
  2. {
  3. public class JsonNetResult : JsonResult
  4. {
  5. public JsonNetResult()
  6. {
  7. Settings = new JsonSerializerSettings
  8. {
  9. ReferenceLoopHandling = ReferenceLoopHandling.Ignore,//忽略循环引用,如果设置为Error,则遇到循环引用的时候报错(建议设置为Error,这样更规范)
  10. DateFormatString = "yyyy-MM-dd HH:mm:ss",//日期格式化,默认的格式也不好看
  11. ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()//json中属性开头字母小写的驼峰命名
  12. };
  13. }
  14.  
  15. public JsonSerializerSettings Settings { get; private set; }
  16.  
  17. public override void ExecuteResult(ControllerContext context)//重写JsonResult类的ExecuteResult方法
  18. {
  19. if (context == null)
  20. throw new ArgumentNullException("context");
  21. //判断是否运行Get请求
  22. if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
  23. && string.Equals(context.HttpContext.Request.HttpMethod,"GET",StringComparison.OrdinalIgnoreCase))
  24. throw new InvalidOperationException("JSON GET is not allowed");
  25. //设定响应数据格式。默认为json
  26. HttpResponseBase response = context.HttpContext.Response;
  27. response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
  28. //设定内容编码格式
  29. if (this.ContentEncoding != null)
  30. response.ContentEncoding = this.ContentEncoding;
  31. if (this.Data == null)
  32. return;
  33. var scriptSerializer = JsonSerializer.Create(this.Settings);
  34. scriptSerializer.Serialize(response.Output,this.Data);
  35.  
  36. }
  37. }

第三步:现在我们看怎么在控制器中使用:

  1. namespace MvcApp.Controllers
  2. {
  3. public class HomeController : Controller
  4. {
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9.  
  10. [HttpPost]
  11. public JsonNetResult TestJson()
  12. {
  13. Person person = new Person() { Id = 1,Name = "张三",CreateTime = DateTime.Now };
  14. //直接这样使用就可以啦
  15. return new JsonNetResult() { Data = person };
  16. }
  17. }
  18.  
  19. public class Person
  20. {
  21. public int Id { get; set; }
  22. public string Name { get; set; }
  23. public DateTime CreateTime { get; set; }
  24. }
  25. }

目的结果:

  1. {id: 1,createTime: "2018-03-25 22:26:07"}

 

第一种扩展 :为了使用方便使用,可以在过滤器中对JsonResult替换成我们自己的JsonNetResult(推荐)

由于直接return new JsonNetResult(){Data=person} 对MVC框架侵入式比较强,用起来还是不是很方便,那么如何尽量保持原来的使用方式不变的情况下来使用我们自定义的JsonNetResult呢?方法很简单,就是使用ActionFilterAttribute过滤器

我们新建一个JsonNetResultAttribute的顾虑器,让它继承ActionFilterAttribute 或者是直接实现IActionFilter接口,我这里是直接选择实现然后实现IActionFilter接口中的OnActionExecuted方法,在这个方法中将原先的JsonReuslt替换成我们的自定义的JsonNetResult,就达到目的了

第一步:自定义一个JsonNetResult过滤器

  1. namespace MvcApp.Filters
  2. {
  3. using MvcApp.Controllers;
  4. using System.Web.Mvc;
  5. public class JsonNetResultAttritube : IActionFilter
  6. {
  7. /// <summary>
  8. /// 注意:OnActionExecuted是在Action方法执行之后被执行
  9. /// 在这里我们将JsonResult替换成我们的JsonNetResult
  10. /// </summary>
  11. /// <param name="filterContext"></param>
  12. public void OnActionExecuted(ActionExecutedContext filterContext)
  13. {
  14. ActionResult result = filterContext.Result;
  15. if (result is JsonResult && !(result is JsonNetResult))
  16. {
  17. JsonResult jsonResult = (JsonResult)result;
  18. JsonNetResult jsonNetResult = new JsonNetResult();
  19. jsonNetResult.ContentEncoding = jsonResult.ContentEncoding;
  20. jsonNetResult.ContentType = jsonResult.ContentType;
  21. jsonNetResult.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
  22. jsonNetResult.Data = jsonResult.Data;
  23. jsonNetResult.MaxJsonLength = jsonResult.MaxJsonLength;
  24. jsonNetResult.RecursionLimit = jsonResult.RecursionLimit;
  25.  
  26. filterContext.Result = jsonNetResult;
  27. }
  28. }
  29.  
  30. public void OnActionExecuting(ActionExecutingContext filterContext)
  31. {
  32.  
  33. }
  34. }
  35. }

第二步:过滤器中注册这个过滤器

  1. namespace MvcApp.App_Start
  2. {
  3. public class FilterConfig
  4. {
  5. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  6. {
  7. filters.Add(new HandleErrorAttribute());
  8. filters.Add(new JsonNetResultAttritube());
  9. }
  10. }
  11. }

第三步:在控制中使用

原来怎么用就怎么用,完全不用任何更改,就达到了我们的目的
  1. namespace MvcApp.Controllers
  2. {
  3. using System.Web.Mvc;
  4. public class HomeController : Controller
  5. {
  6. public ActionResult Index()
  7. {
  8. return View();
  9. }
  10.  
  11. [HttpPost]
  12. public JsonResult TestJson()
  13. {
  14. Person person = new Person() { Id = 1,CreateTime = DateTime.Now };
  15. //原来该怎么用还是怎么用(只是通过过滤器,我们将这个Json(person)替换成我们自己的JsonNetResult了)
  16. return Json(person);
  17. }
  18. }
  19.  
  20. public class Person
  21. {
  22. public int Id { get; set; }
  23. public string Name { get; set; }
  24. public DateTime CreateTime { get; set; }
  25. }
  26. }

目的结果:

  1. {id: 1,createTime: "2018-03-25 22:26:07"}


第二种扩展:是对控制器做一些扩展,也可以让使用更加方便

第一步:扩展控制器

  1. public static class ControllerExpand
  2. {
  3. public static JsonNetResult JsonNet(this Controller JsonNet,object data)
  4. {
  5. return new JsonNetResult() { Data = data };
  6. }
  7.  
  8. public static JsonNetResult JsonNet(this Controller JonsNet,object data,JsonRequestBehavior behavior)
  9. {
  10. return new JsonNetResult()
  11. {
  12. Data = data,JsonRequestBehavior = behavior
  13. };
  14. }
  15.  
  16. public static JsonNetResult JsonNet(this Controller JonsNet,string contentType,Encoding contentEncoding)
  17. {
  18. return new JsonNetResult()
  19. {
  20. Data = data,ContentType = contentType,ContentEncoding = contentEncoding
  21. };
  22. }
  23.  
  24. public static JsonNetResult JsonNet(this System.Web.Mvc.Controller JonsNet,Encoding contentEncoding,JsonRequestBehavior behavior)
  25. {
  26. return new JsonNetResult()
  27. {
  28. Data = data,ContentEncoding = contentEncoding,JsonRequestBehavior = behavior
  29. };
  30. }
  31. }

第二步:在控制器中使用

  1. namespace MvcApp.Controllers
  2. {
  3. public class HomeController : Controller
  4. {
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9.  
  10. [HttpPost]
  11. public JsonNetResult TestJson()
  12. {
  13. Person person = new Person() { Id = 1,CreateTime = DateTime.Now };
  14. //直接这样使用就可以啦
  15. //return new JsonNetResult() { Data = person };
  16.  
  17. //这样使用是不是更加方便了呢?哈哈
  18. return this.JsonNet(person);
  19. }
  20. }
  21.  
  22. public class Person
  23. {
  24. public int Id { get; set; }
  25. public string Name { get; set; }
  26. public DateTime CreateTime { get; set; }
  27. }
  28. }

目的结果:

    1. {id: 1,createTime: "2018-03-25 22:26:07"}

 

使用Newtonsoft.Json 解决Json日期格式问题

posted on 2021-04-01 14:30  大西瓜3721  阅读(365)  评论(0编辑  收藏  举报

导航