技术标签: Mvc
Asp.Net MVC默认是使用JavaScriptSerializer做Json序列化的,不好用。而且JavaScriptSerializer无法处理循环引用,对日期的格式化不友好。例如对当前日期序列化后的效果是这样的:【CreateTime: "/Date(1521983727837)/"】 这样的日期我们很难看懂
而且JavaScriptSerializer对一个对象的序列化,序列化后的json对象属性与C#中的对象的属性名称一致。因为我们在javascript中习惯将对象属性的第一个字母是以小写开头的,不习惯属性的第一个字母是大写开头的,比如:,比如 id,name,createTime举列:
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"}
或者执行PM>Install-Package Newtonsoft.Json -Version 11.0.2
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"}
由于直接return new JsonNetResult(){Data=person} 对MVC框架侵入式比较强,用起来还是不是很方便,那么如何尽量保持原来的使用方式不变的情况下来使用我们自定义的JsonNetResult呢?方法很简单,就是使用ActionFilterAttribute过滤器
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"}
文章浏览阅读4.9w次,点赞7次,收藏11次。有位用户在使用PR模板制作视频时,遇到PR导出出错的问题,问题描述:编译影片时出错,加速渲染器错误”(如下图所示)编译影片时出错。GPU渲染错误无法处理帧。这部分因视频内容不同而出错提示不同,所以省略…组件EfedFillert类型 GPU视频滤镜选择器:9错误代码:-1609629695于是亲测该PR模板:PR模板 卖房售房租房酒店促销等产品幻灯片展示PR视频模板找到了解决办法。如果你也遇到同样问题,可以尝试下面的方法哦。1、点击菜单“文件”,选则“项目设置”,点击“常规”。如._-1609629695
文章浏览阅读4k次,点赞6次,收藏5次。将 Anaconda3 的路径添加到环境变量中,在cmd先运行activate root 在运行jupyter notebook。_jupyter notebook 导入库 报错 importerror: dll load failed while importing _a
文章浏览阅读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._手机行业专业术语
文章浏览阅读1.3k次。项目需要做一个简单的播放视频功能demo,考虑到需求较简单(实现不超过2min的MP4格式短视频播放),所以就没考虑使用复杂的第三方视频库了。最初敲定使用系统原生的VideoView实现,后来发现不能在列表中使用普通的VideoView 。VideoView 继承自SurfaceView,而SurfaceView并没有UI同步缓冲区。这就导致了在列表滚动的时候,正在播放的视频可能无法跟上滚动的_texttureview mediaplayer
文章浏览阅读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爱好者|阅次元论坛|菜鸟图库|魅族社区|经管之家|有分享_微博超话签到 青龙面板
文章浏览阅读2.2k次。 tx2内部集成了can控制器,用的是Bosch的芯片。can的驱动在tx2内核中被注册为网络设备也就是socket can,说到这里相信很多人已经猜到了驱动的大致架构,下面记录了我分析驱动的过程。 首先该驱动还是遵循platform架构,所以我们这里就直接进入到probe函数了。static int mttcan_probe(struct platform_devic..._mttcan
文章浏览阅读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
文章浏览阅读3.4k次,点赞3次,收藏8次。springboot的Profile(用于快速切换开发环境),涉及到profile的加载顺序,list值的覆盖,map元素的添加_springboot profiles
文章浏览阅读751次。决策树是一种树形分类模型,每个非叶子结点相当于if条件语句,通过逐个判定特征所属类别进行分类。那么,决策树模型具体是如何实现的?_决策树输出值只有0.0几,泛化能力怎么样
文章浏览阅读2.3k次。http://baike.baidu.com/view/560845.htm释义 晴天娃娃,又称扫晴娘,扫天婆,放晴娘,晴天和尚。流行于中国农村和日本,是一种悬挂在屋檐上祈求晴天的布偶。 “晴天娃娃”的日文:照る照る坊主 (teru teru bouzu) 照る (てる teru) 坊主 (ぼうず bouzu) 日本的一部动画片《一休和尚_放晴娘图片