使用Newtonsoft.json 解决 Asp.Net MVC DateTime类型数据Json格式化问题
解决思路
众所周知,MVC中调用的微软的组件JavaScriptSerialer...,格式DateTime类型数据需要在客户端专门解。
还知道,NewtonSoft.json可以“正确”的格式化DateTime类型的数据。
但是,如果在MVC中使用NewtonSoft.json的话,则需要调用Controller.Content(),返回的为字符串,客户端还要做转换。
而,Action返回的结果都是JsonResult。
于是,我用NewtonSoft.json的方法封装了一个NewtonJsonReuslt的类型,供Controller调用,具体的参考的MVC JsonResult的源码,没有技术含量。
代码部分
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters; namespace System.Web.Mvc
{
public class NewtonJsonResult : JsonResult
{
public JsonSerializerSettings JsonSerializerSettings { get; set; }
public NewtonJsonResult()
{
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public NewtonJsonResult(object obj)
{
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
this.Data = obj;
}
public NewtonJsonResult(object obj,JsonSerializerSettings jsonSerializerSettings)
{
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
this.Data = obj;
this.JsonSerializerSettings = jsonSerializerSettings;
} 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("改方法当前不允许使用Get");
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
string strJson = JsonConvert.SerializeObject(this.Data, JsonSerializerSettings);
response.Write(strJson);
response.End();
}
}
}
}
查看代码
调用demo:
public ActionResult Get(int pageIndex)
{
IArticleService service = new ArticleService();
int allPageCount;
List<Model.Article> list = service.GetArticleByPage(PAGESIZE, pageIndex, out allPageCount);
return new NewtonJsonResult(list, new JsonSerializerSettings() { DateFormatString="yyyy年MM月dd日 HH:mm:ss" });
}
查看代码
上面代码随手写的,有错误,望大家勿喷...
另外,还写了静态的ControllBase扩展方法
using System.Text;
using System.Web.Mvc; namespace System.Web.Mvc
{
public static class ControllerExtend
{
public static ActionResult NewtonJson(this ControllerBase controller, object obj)
{
return NewtonJson(controller, null, null, JsonRequestBehavior.DenyGet, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, Encoding encoding, string contentType, JsonRequestBehavior jsonRequestBehavior, object obj)
{
return new NewtonJsonResult() { ContentEncoding = encoding, ContentType = contentType, JsonRequestBehavior = jsonRequestBehavior, Data = obj };
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, JsonRequestBehavior jsonRequestBehavior)
{
return NewtonJson(controller, null, null, jsonRequestBehavior, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, Encoding encoding, JsonRequestBehavior jsonRequestBehavior)
{
return NewtonJson(controller, encoding, null, jsonRequestBehavior, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, string contentType)
{
return NewtonJson(controller, null, contentType, JsonRequestBehavior.DenyGet, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, Encoding encoding)
{
return NewtonJson(controller, encoding, null, JsonRequestBehavior.DenyGet, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, Encoding encoding, string contentType)
{
return NewtonJson(controller, encoding, contentType, JsonRequestBehavior.DenyGet, obj);
}
public static ActionResult NewtonJson(this ControllerBase controller, object obj, Encoding encoding, string contentType, JsonRequestBehavior jsonRequestBehavior)
{
return NewtonJson(controller, encoding, contentType, jsonRequestBehavior, obj);
}
}
}
查看代码
不过,调用的时候有点小问题,看下面的最后两个return语句,不太明白为什么扩展方法必须要写一个对象去调用?难道是扩展方法中的第一个参数导致的必须写?还望路过的大侠给小弟解惑,小弟不胜感激...
public ActionResult Get(int pageIndex)
{
IArticleService service = new ArticleService();
int allPageCount;
List<Model.Article> list = service.GetArticleByPage(PAGESIZE, pageIndex, out allPageCount);
return new NewtonJsonResult(list, new JsonSerializerSettings() { DateFormatString="yyyy年MM月dd日 HH:mm:ss" });
return NewtonJson(list);//这样是直接报错的,找不到方法,必须按照下面的写法才行..
return this.NewtonJson(list);
}
使用Newtonsoft.json 解决 Asp.Net MVC DateTime类型数据Json格式化问题的更多相关文章
- 解决python中转化成json的方法不能序列化datetime类型数据(转)
Python自带的json.dumps方法序列化数据时候如果格式化的数据中有datetime类型数据时候会提示错误TypeError: datetime.datetime(2012, 12, 12, ...
- JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List转JSON,JSON转List,JSON转C#对象
一.JSON解析与字符串化 JSON.stringify() 序列化对象.数组或原始值 语法:JSON.stringify(o,filter,indent) o,要转换成JSON的对象.数组或原始值 ...
- JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List<T>转JSON,JSON转List<T>,JSON转C#对象
一.JSON解析与字符串化 JSON.stringify() 序列化对象.数组或原始值 语法:JSON.stringify(o,filter,indent) o,要转换成JSON的对象.数组或原始值 ...
- 解决Win10系统下 C# DateTime 出现星期几的问题 解决ASP.NET MVC 接受Request Playload参数问题
解决Win10系统下 C# DateTime 出现星期几的问题 昨天晚上写代码的时候偶然发现 DateTime 里出现了星期几,当时一阵凌乱,去网上百度没有详细解决办法,很多人说可以用用 ToStri ...
- 自定义JsonResult处理JSON序列化DateTime类型数据(Ext4.2+ASP.NET MVC 4)
最近项目中前台页面使用Extjs4.2 ,在后台ASP.NET MVC4返回的DateTime类型的数据错返回的DateTime类型的JsonResult的结果中的值是“\/Date(13784461 ...
- 【ASP.NET MVC系列】数据验证和注解
[01]浅谈Google Chrome浏览器(理论篇) [02]浅谈Google Chrome浏览器(操作篇)(上) [03]浅谈Google Chrome浏览器(操作篇)(下) [04]浅谈ASP. ...
- Asp.Net Mvc 返回类型总结
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- ASP.NET MVC 描述类型(二)
ASP.NET MVC 描述类型(二) 前言 上个篇幅中说到ControllerDescriptor类型的由来过程,对于ControllerDescriptor类型来言ActionDescriptor ...
- ASP.NET MVC 描述类型(一)
ASP.NET MVC 描述类型(一) 前言 在前面的好多篇幅中都有提到过ControllerDescriptor类型,并且在ASP.NET MVC 过滤器(一)篇幅中简单的描述过,今天我们就来讲一下 ...
随机推荐
- python DataFrame索引选项
obj[val]-----------选取DataFrame的单个列或一组列,在一些情况下会比较便利:布尔型数组(过滤行).切片(行切片).布尔型DataFrame obj.ix[val]------ ...
- WebStorm 预览时把浏览器地址localhost 改成IP
最近在使用WebStorm时,预览网页时地址总是显示的 http://localhost:63342/... ,如果要调试其它设备感觉很不方法,此时肯定首先想到的亲爱的度娘,但是貌似没有真正很解决问题 ...
- stm32 输入捕获学习(二)
(本文参考STM32 开发指南 V1.3 -- ALIENTEK 战舰 STM32 开发板库函数教程 ) 1. 实验设计 我们用 TIM5 的通道 1(PA0)来做输入捕获,捕获 PA0 上高电 ...
- pat1086. Tree Traversals Again (25)
1086. Tree Traversals Again (25) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...
- .vimrc的配置
set nocompatible set encoding=utf-8 set fileencodings=utf-8,chinese set tabstop=4 set cindent shiftw ...
- genymotion安装及使用出现的问题
此处总结genymotion出现的问题. 1)安装好genymotion后,新建一个模拟器.去下载的时候报错 Unable to create Virtual Device: Connection t ...
- vscode好用的扩展及常用的快捷键
1.open-in-browser 或者view in browser 安装后右键即可快速打开浏览器 2.quokka调试工具插件,能对正在编写的代码提供实时反馈,并能预览变量的函数和计算结果 3. ...
- springmvc源码分析上之HandlerMapping
现在企业开发中,必不可少的管理框架就是spring,而与之搭配的也是企业开发中用的最多的MVC框架:Springmvc 关于springmvc原理,请自行百度 HandlerMapping是sprin ...
- 简单二级导航JQ事件代码
$(function()){ $("li").hover(function(){ $(this).children("dl").show() },functio ...
- 关于jqeury中attr()和prop()方法
在平时工作中老会被一样的问题困住,浪费时间,这里做一个简要笔记. 在使用jquery给元素设置属性的时候,如果是一般的div,p等正常元素设置属性的话,使用attr()足以,但是在给拥有checked ...