使用Newtonsoft.Json 解决Json日期格式问题_mvcnewtonsoftjsonoptions 日期格式配置-程序员宅基地

技术标签: Mvc  

介绍

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 DateTime CreateTime { get; set; }
}
如果使用JavaScriptSerializer对这个对象序列化,序列化后的效果是这样的:
{Id: 1, Name: "张三", CreateTime: "/Date(1521983727837)/"}

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

{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类

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.HttpMethod, "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);

        }
    }

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

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

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

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreateTime { get; set; }
    }
}

目的结果:

{id: 1, name: "张三", 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, Name = "张三", CreateTime = DateTime.Now };
            //原来该怎么用还是怎么用(只是通过过滤器,我们将这个Json(person)替换成我们自己的JsonNetResult了)
            return Json(person);
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreateTime { get; set; }
    }
}

目的结果:

{id: 1, name: "张三", 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,object data, string contentType, Encoding contentEncoding)
    {
        return new JsonNetResult()
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding
        };
    }

    public static JsonNetResult JsonNet(this System.Web.Mvc.Controller JonsNet, object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonNetResult()
        {
            Data = data,
            ContentType = contentType,
            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, Name = "张三", CreateTime = DateTime.Now };
            //直接这样使用就可以啦
            //return new JsonNetResult() { Data = person };  

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

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreateTime { get; set; }
    }
}

目的结果:

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



版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Fanbin168/article/details/79691503

智能推荐

PR导出错误怎么办?解决PR导出视频提示“编译影片时出错“ GPU渲染错误 错误代码:-1609629695-程序员宅基地

文章浏览阅读4.9w次,点赞7次,收藏11次。有位用户在使用PR模板制作视频时,遇到PR导出出错的问题,问题描述:编译影片时出错,加速渲染器错误”(如下图所示)编译影片时出错。GPU渲染错误无法处理帧。这部分因视频内容不同而出错提示不同,所以省略…组件EfedFillert类型 GPU视频滤镜选择器:9错误代码:-1609629695于是亲测该PR模板:PR模板 卖房售房租房酒店促销等产品幻灯片展示PR视频模板找到了解决办法。如果你也遇到同样问题,可以尝试下面的方法哦。1、点击菜单“文件”,选则“项目设置”,点击“常规”。如._-1609629695

window10 jupyter notebook 遇到‘ImportError: DLL load failed: 找不到指定的模块。’的问题_jupyter notebook 导入库 报错 importerror: dll load fail-程序员宅基地

文章浏览阅读4k次,点赞6次,收藏5次。将 Anaconda3 的路径添加到环境变量中,在cmd先运行activate root 在运行jupyter notebook。_jupyter notebook 导入库 报错 importerror: dll load failed while importing _a

Spring Cloud Stream App Starters-程序员宅基地

文章浏览阅读50次。Spring Cloud Stream Application Starters are standalone executable applications that communicate over messaging middleware such as Apache Kafka and RabbitMQ. These applications can run independently o...

手机专业名词详解_手机行业专业术语-程序员宅基地

文章浏览阅读1.5w次。 手机专业名词详解 专业名词详解... 11、 手机制式... 61.1 GSM.. 61.2 CDMA. 61.3 3G.. 71.4 W-CDMA. 71.5 CDMA2000. 71.6 TD-SCDMA. 71._手机行业专业术语

MediaPlayer+TextureView全屏播放视频_texttureview mediaplayer-程序员宅基地

文章浏览阅读1.3k次。项目需要做一个简单的播放视频功能demo,考虑到需求较简单(实现不超过2min的MP4格式短视频播放),所以就没考虑使用复杂的第三方视频库了。最初敲定使用系统原生的VideoView实现,后来发现不能在列表中使用普通的VideoView 。VideoView 继承自SurfaceView,而SurfaceView并没有UI同步缓冲区。这就导致了在列表滚动的时候,正在播放的视频可能无法跟上滚动的_texttureview mediaplayer

0/1 nodes are available: 1 node(s) had taints that the pod didn't tolerate.-程序员宅基地

文章浏览阅读2w次,点赞3次,收藏10次。允许master节点部署podkubectl taint nodes --all node-role.kubernetes.io/master-_0/1 nodes are available: 1 node(s) had taints that the pod didn't tolerate.

随便推点

青龙面板-签到合集_微博超话签到 青龙面板-程序员宅基地

文章浏览阅读1.1w次,点赞3次,收藏27次。常用网站签到本地/云函数/青龙脚本( 人人视频|刺猬猫小说|Acfun|WPS| 时光相册|书香门第论坛|绅士领域|好游快爆|埋堆堆|多看阅读|一亩三分地|闪艺app|香网小说|晋江|橙光|什么值得买|网易蜗牛读书|网易云游戏平台|龙空论坛|NGA论坛|csdn|mt论坛|sf轻小说|猫耳FM|联想智选app|联想智选联想延保|联动云租车|数码之家|玩物志好物商店|togamemod|好书友论坛|鱼C论坛|帆软社区|村花论坛|纪录片之家|富贵论坛|ug爱好者|阅次元论坛|菜鸟图库|魅族社区|经管之家|有分享_微博超话签到 青龙面板

jetson-tx2平台mttcan驱动分析-程序员宅基地

文章浏览阅读2.2k次。 tx2内部集成了can控制器,用的是Bosch的芯片。can的驱动在tx2内核中被注册为网络设备也就是socket can,说到这里相信很多人已经猜到了驱动的大致架构,下面记录了我分析驱动的过程。 首先该驱动还是遵循platform架构,所以我们这里就直接进入到probe函数了。static int mttcan_probe(struct platform_devic..._mttcan

turple list dict 互相转换-程序员宅基地

文章浏览阅读1k次。1. 字典(dict)dict = {‘name’: ‘Zara’, ‘age’: 7, ‘class’: ‘First’}1.1 字典---字符串print (type(str(dict)), str(dict))结果如下<class 'str'> {'name': 'Zara', 'age': 7, 'class': 'First'}1.2 字典---元组p..._tubles 转为 dict

22、springboot 的 Profile(通过yml配置文件配置 profile,快速切换项目的开发环境)_springboot profiles-程序员宅基地

文章浏览阅读3.4k次,点赞3次,收藏8次。springboot的Profile(用于快速切换开发环境),涉及到profile的加载顺序,list值的覆盖,map元素的添加_springboot profiles

机器学习方法篇(3)------决策树入门_决策树输出值只有0.0几,泛化能力怎么样-程序员宅基地

文章浏览阅读751次。决策树是一种树形分类模型,每个非叶子结点相当于if条件语句,通过逐个判定特征所属类别进行分类。那么,决策树模型具体是如何实现的?_决策树输出值只有0.0几,泛化能力怎么样

一休和尚 小布偶 晴天娃娃_放晴娘图片-程序员宅基地

文章浏览阅读2.3k次。http://baike.baidu.com/view/560845.htm释义  晴天娃娃,又称扫晴娘,扫天婆,放晴娘,晴天和尚。流行于中国农村和日本,是一种悬挂在屋檐上祈求晴天的布偶。  “晴天娃娃”的日文:照る照る坊主 (teru teru bouzu)   照る (てる teru)   坊主 (ぼうず bouzu)   日本的一部动画片《一休和尚_放晴娘图片