解决思路

众所周知,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格式化问题的更多相关文章

  1. 解决python中转化成json的方法不能序列化datetime类型数据(转)

    Python自带的json.dumps方法序列化数据时候如果格式化的数据中有datetime类型数据时候会提示错误TypeError: datetime.datetime(2012, 12, 12, ...

  2. JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List转JSON,JSON转List,JSON转C#对象

    一.JSON解析与字符串化 JSON.stringify() 序列化对象.数组或原始值 语法:JSON.stringify(o,filter,indent) o,要转换成JSON的对象.数组或原始值 ...

  3. 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的对象.数组或原始值 ...

  4. 解决Win10系统下 C# DateTime 出现星期几的问题 解决ASP.NET MVC 接受Request Playload参数问题

    解决Win10系统下 C# DateTime 出现星期几的问题 昨天晚上写代码的时候偶然发现 DateTime 里出现了星期几,当时一阵凌乱,去网上百度没有详细解决办法,很多人说可以用用 ToStri ...

  5. 自定义JsonResult处理JSON序列化DateTime类型数据(Ext4.2+ASP.NET MVC 4)

    最近项目中前台页面使用Extjs4.2 ,在后台ASP.NET MVC4返回的DateTime类型的数据错返回的DateTime类型的JsonResult的结果中的值是“\/Date(13784461 ...

  6. 【ASP.NET MVC系列】数据验证和注解

    [01]浅谈Google Chrome浏览器(理论篇) [02]浅谈Google Chrome浏览器(操作篇)(上) [03]浅谈Google Chrome浏览器(操作篇)(下) [04]浅谈ASP. ...

  7. Asp.Net Mvc 返回类型总结

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  8. ASP.NET MVC 描述类型(二)

    ASP.NET MVC 描述类型(二) 前言 上个篇幅中说到ControllerDescriptor类型的由来过程,对于ControllerDescriptor类型来言ActionDescriptor ...

  9. ASP.NET MVC 描述类型(一)

    ASP.NET MVC 描述类型(一) 前言 在前面的好多篇幅中都有提到过ControllerDescriptor类型,并且在ASP.NET MVC 过滤器(一)篇幅中简单的描述过,今天我们就来讲一下 ...

随机推荐

  1. Unity 在Inspector面板,脚本前面的激活对勾

    写个脚本,把它挂在一个游戏对象上: using System.Collections; using System.Collections.Generic; using UnityEngine; pub ...

  2. 几种常见的排序算法Java实现总结

    public class MySort { final int MAX=20; int num[]=new int[MAX]; { System.out.print("生成的随机数组是:&q ...

  3. 单元测试-Junit-Mockit-PowerMock

    0. Junit5 1. Junit4 //手动命令行测试 java -cp /usr1/junit:/usr1/cdncms/lib/* org.junit.runner.JUnitCore com ...

  4. 转-Shell笔记——命令:Sort,uniq,join,cut,paste,split

    转自:http://blog.csdn.net/wklken/article/details/6562098 Sort,uniq,join,cut,paste,split 命令—— Sort Sort ...

  5. 支付宝php支付接口说明

    直接把该代码放到PHP服务器下,直接访问index.php.1.文件列表: alipay_config.php    (基本参数配置页面,填写商家的支付宝安全校验码,合作id,支付宝帐号等内容)ind ...

  6. Qt 学习(3)

    Qt 修改 Windows 注册表项 在使用 FT232R 驱动(usb转串口设备)连接电脑时,下位机发送的数据会被转换器缓存起来,由串口转换器驱动设定的延时定时发送到 PC,这样就造成了一个问题:上 ...

  7. PHPcms的安装步骤

    http://www.phpcms.cn 制作良好习惯: 1.备份 2.随时保存 3.注释 在自己的PHP环境里 简历一个文件夹 比如命名为YiNong 访问安装地址,http://localhost ...

  8. Tomcat实现Session共享

    一个Tomcat中有多一个web应用,然后想共享session,只需在host中加上 <Valve className="org.apache.catalina.authenticat ...

  9. git分支合并冲突

    合并冲突 如果你在两个不同的分支中,对同一个文件的同一个部分进行了不同的修改,Git 就没法干净的合并它们. 如果你对 #53 问题的修改和有关 hotfix 的修改都涉及到同一个文件的同一处,在合并 ...

  10. C#获取文件格式图标关联应用程序图标

    class SystemIcon { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct SHFIL ...