Json   发布时间:2022-04-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用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了

举列:

public class Person
{
    public int id { get; set; }
    public String Name { get; set; }
    public datetiR_429_11845@e CreateTime { get; set; }
}
如果使用JavaScriptserializer对这个对象序列化,序列化后的效果是这样的
{Id: 1,Name: "张三",CreateTime: "/Date(1521983727837)/"}

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

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

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

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

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

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

namespace MvcApp.Controllers
{
    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)//重写JsonResult类的ExecuteResult方法
        {
            if (context == null)
                throw new ArgumentNullException("context");
            //判断是否运行Get请求
            if (this.JsonrequestBehavior == JsonrequestBehavior.DenyGet
                && String.Equals(context.httpContext.request.httpR_429_11845@ethod,"GET",StringComparison.ordinalIgnoreCasE))
                throw new InvalidoperationException("JSON GET is not allowed");
            //设定响应数据格式。认为json
            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);

        }
    }

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

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {         
            return View();
        }

        [httpPost]
        public JsonNetResult TestJson()
        {
            Person person = new Person() { Id = 1,Name = "张三",CreateTime = datetiR_429_11845@e.Now };
            //直接这样使用就可以啦
            return new JsonNetResult() { Data = person };                
        }
    }

    public class Person
    {
        public int id { get; set; }
        public String Name { get; set; }
        public datetiR_429_11845@e CreateTime { get; set; }
    }
}

目的结果:

{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过滤器

namespace MvcApp.Filters
{
    using MvcApp.Controllers;
    using System.Web.Mvc;
    public class JsonNetResultAttritube : IActionFilter
    {
        /// <sumMary>
        /// 注意:OnActionExecuted是在Action方法执行之后被执行
        /// 在这里我们将JsonResult替换成我们的JsonNetResult
        /// </sumMary>
        /// <param name="filterContext"></param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ActionResult result = filterContext.Result;
            if (result is JsonResult && !(result is JsonNetResult))
            {
                JsonResult jsonResult = (JsonResult)result;
                JsonNetResult jsonNetResult = new JsonNetResult();
                jsonNetResult.ContentEncoding = jsonResult.ContentEncoding;
                jsonNetResult.ContentType = jsonResult.ContentType;
                jsonNetResult.JsonrequestBehavior = jsonResult.JsonrequestBehavior;
                jsonNetResult.Data = jsonResult.Data;
                jsonNetResult.MaxJsonLength = jsonResult.MaxJsonLength;
                jsonNetResult.RecursionLimit = jsonResult.RecursionLimit;

                filterContext.Result = jsonNetResult; 
            }
        }

        public void OnActionExecuTing(ActionExecuTingContext filterContext)
        {

        }
    }
}

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

namespace MvcApp.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new JsonNetResultAttritube());
        }
    }
}

第三步:在控制中使用

原来怎么用就怎么用,完全不用任何更改,就达到了我们的目的
namespace MvcApp.Controllers
{
    using System.Web.Mvc;
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [httpPost]
        public JsonResult TestJson()
        {
            Person person = new Person() { Id = 1,CreateTime = datetiR_429_11845@e.Now };
            //原来该怎么用还是怎么用(只是通过过滤器,我们将这个Json(person)替换成我们自己的JsonNetResult了)
            return Json(person);
        }
    }

    public class Person
    {
        public int id { get; set; }
        public String Name { get; set; }
        public datetiR_429_11845@e CreateTime { get; set; }
    }
}

目的结果:

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


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

第一步:扩展控制器

public static class ControllerExpand
{
    public static JsonNetResult JsonNet(this Controller JsonNet,object data)
    {
        return new JsonNetResult() { Data = data };
    }

    public static JsonNetResult JsonNet(this Controller JonsNet,object data,JsonrequestBehavior behavior)
    {
        
        return new JsonNetResult()
        {
            Data = data,JsonrequestBehavior = behavior
        };
    }

    public static JsonNetResult JsonNet(this Controller JonsNet,String contentType,Encoding contentEncoding)
    {
        return new JsonNetResult()
        {
            Data = data,Contenttype = contentType,ContentEncoding = contentEncoding
        };
    }

    public static JsonNetResult JsonNet(this System.Web.Mvc.Controller JonsNet,Encoding contentEncoding,JsonrequestBehavior behavior)
    {
        return new JsonNetResult()
        {
            Data = data,ContentEncoding = contentEncoding,JsonrequestBehavior = behavior
        };
    }
}

第二步:在控制器中使用

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {         
            return View();
        }

        [httpPost]
        public JsonNetResult TestJson()
        {
            Person person = new Person() { Id = 1,CreateTime = datetiR_429_11845@e.Now };
            //直接这样使用就可以啦
            //return new JsonNetResult() { Data = person };  

            //这样使用是不是更加方便了呢?哈哈
            return this.JsonNet(person);              
        }
    }

    public class Person
    {
        public int id { get; set; }
        public String Name { get; set; }
        public datetiR_429_11845@e CreateTime { get; set; }
    }
}

目的结果:

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

大佬总结

以上是大佬教程为你收集整理的使用Newtonsoft.Json 解决Json日期格式问题全部内容,希望文章能够帮你解决使用Newtonsoft.Json 解决Json日期格式问题所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。