使用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 过滤器(一)篇幅中简单的描述过,今天我们就来讲一下 ...
随机推荐
- spring配置文件中util:properties和context:property-placeholder
util:properties和context:property-placeholder标签都可以用来获取外部配置文件中的内容 1.util:properties 它是以声明bean方式来使用,创建了 ...
- oracle命令查看表结构及表索引
--查看oracle数据库的单个表结构 select dbms_metadata.get_ddl('TABLE','TABLE_NAME') from dual; 括号里面有两个参数,第一个参数是我们 ...
- JobService 7.0 定时任务不生效
代码 // 构建JobInfo对象,传递给JobSchedulerService JobInfo.Builder builder = new JobInfo.Builder(JOB_ID,new Co ...
- CSAPP阅读笔记-链接-第七章-P464-P500
链接概述 经预处理器->编译器->汇编器处理后,源文件可被转化为一组可重定位目标文件,链接器将它们组合起来形成可执行文件. 每个可重定位目标文件由不同的“代码节”和“数据节”组成,每一个节 ...
- MATLAB特殊矩阵以及矩阵转置
特殊矩阵 通用特殊矩阵 zeros函数:产生全0矩阵,即零矩阵. ones函数:产生....1矩阵,即幺矩阵. eye函数:产生对角线为1的矩阵,当矩阵是方正时,得到单位矩阵. rand函数:产生(0 ...
- Java Executors小结
一 Executors提供了一系列工厂方法用于创先线程池ThreadPoolExecutor线程池的具体实现类,一般用的各种线程池都是基于这个类实现的 返回的线程池都实现了ExecutorServic ...
- 远程登陆服务器(window系统)
1,打开命令输入框: 快捷键:win+R 2.输入命令:mstsc 3.输入你的IP地址和用户名(一般为administrator) 4.输入密码
- gulp 无损压缩图片
在做项目中,美工有时候会给一些比较大的图片,在做网站的时候,图片太大会影响加载速度.因此,我们需要无损压缩图片. 在尝试过几个压缩图片的方法,发现gulp中的gulp-tinypng-nokey插件是 ...
- php session 存储到redis
PHP 的会话默认是以文件的形式存在的,可以配置到 NoSQL 中,即提高了访问速度,又能很好地实现会话共享,,,爽歪歪! 配置方式如下: 方法一:修改 php.ini 的设置 1 2 session ...
- 在页面rem布局中用到的js代码
在你的页面加入以下代码,就初步搞定了 function fontSize() { var view_width = document.getElementsByTagName('html')[0].g ...