解决Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的方法

所属分类: 网络编程 / ASP.NET 阅读数: 1026
收藏 0 赞 0 分享

问题背景:

           在使用asp.net mvc 结合jquery esayui做一个系统,但是在使用使用this.json方法直接返回一个json对象,在列表中显示时发现datetime类型的数据在转为字符串是它默认转为Date(84923838332223)的格式,在经过查资料发现使用前端来解决这个问题的方法不少,但是我又发现在使用jquery easyui时,加载列表数据又不能对数据进行拦截,进行数据格式转换之后再加载,后来发现可以通过自定义JsonResult实现,认为这种方法比较可行,就开始研究

我们先来看看jsonResult的源码

public class JsonResult : ActionResult
  {
    public JsonResult()
    {
      this.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet;
    }
    
    public override void ExecuteResult(ControllerContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }
      if ((this.JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
      {
        throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
      }
      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)
      {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        response.Write(serializer.Serialize(this.Data));
      }
    }
    
    public Encoding ContentEncoding { get; set; }
    
    public string ContentType { get; set; }
    
    public object Data { get; set; }
    
    public System.Web.Mvc.JsonRequestBehavior JsonRequestBehavior { get; set; }
  }
}

当我看到上面代码中的红色部分,我感到有些熟悉,心里比较高兴,以前使用过ashx来传json的都应该用过此方法吧

原来它也是使用这个方法进行序列化的。我们就可以在这个地方先获取到json序列化之后的字符串!然后做写“小动作”,就ok了

下面我就定义了一个自己的JsonResult了

/// <summary>
  /// 自定义Json视图
  /// </summary>
  public class CustomJsonResult:JsonResult
  {
    /// <summary>
    /// 格式化字符串
    /// </summary>
    public string FormateStr
    {
      get;
      set;
    }

    /// <summary>
    /// 重写执行视图
    /// </summary>
    /// <param name="context">上下文</param>
    public override void ExecuteResult(ControllerContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }

      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)
      {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        string jsonString = jss.Serialize(Data);
        string p = @"\\/Date\((\d+)\)\\/";
        MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
        Regex reg = new Regex(p);
        jsonString = reg.Replace(jsonString, matchEvaluator);

        response.Write(jsonString);
      }
    }

     /// <summary> 
    /// 将Json序列化的时间由/Date(1294499956278)转为字符串 .
    /// </summary> 
    /// <param name="m">正则匹配</param>
    /// <returns>格式化后的字符串</returns>
    private string ConvertJsonDateToDateString(Match m)
    {
      string result = string.Empty;
      DateTime dt = new DateTime(1970, 1, 1);
      dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
      dt = dt.ToLocalTime();
      result = dt.ToString(FormateStr);
      return result;
    }
  }


在这里做的“小动作”就是红色部分,得到字符串以后,通过正则表达式的方式获得Date(12347838383333)的字符串,然后把它转换为DateTime类型,最后在转为我们想要的格式即可,这个格式可以使用FormateStr属性设置。

剩下的就是使用我们自己定义的JsonResult来替换asp.net mvc默认的JsonResult的问题了,接着从源码中找答案,下面是Controller类的部分代码

protected internal JsonResult Json(object data)
    {
      return this.Json(data, null, null, JsonRequestBehavior.DenyGet);
    }
    
    protected internal JsonResult Json(object data, string contentType)
    {
      return this.Json(data, contentType, null, JsonRequestBehavior.DenyGet);
    }
    
    protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
    {
      return this.Json(data, null, null, behavior);
    }
    
    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
    {
      return this.Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
    }
    
    protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
    {
      return this.Json(data, contentType, null, behavior);
    }
    
    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
      return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
    }

以上是Controller类来实例化JsonResult的所有代码。我们只需写一个BaseController类,重写最后一个方法即可,然后我们自己的Controller在继承BaseController即可

下面是BaseController类的部分代码,我们为方便自己个性化的需要又定义了两个MyJosn的方法

/// <summary>
    /// 返回JsonResult
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="contentType">内容类型</param>
    /// <param name="contentEncoding">内容编码</param>
    /// <param name="behavior">行为</param>
    /// <returns>JsonReuslt</returns>
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
      return new CustomJsonResult
      {
        Data = data,
        ContentType = contentType,
        ContentEncoding =contentEncoding,
        JsonRequestBehavior = behavior,
        FormateStr = "yyyy-MM-dd HH:mm:ss"
      };
    }

    /// <summary>
    /// 返回JsonResult.24     /// </summary>
    /// <param name="data">数据</param>
    /// <param name="behavior">行为</param>
    /// <param name="format">json中dateTime类型的格式</param>
    /// <returns>Json</returns>
    protected JsonResult MyJson(object data, JsonRequestBehavior behavior,string format)
    {
      return new CustomJsonResult
      {
        Data = data,
        JsonRequestBehavior = behavior,
        FormateStr = format
      };
    }

    /// <summary>
    /// 返回JsonResult42     /// </summary>
    /// <param name="data">数据</param>
    /// <param name="format">数据格式</param>
    /// <returns>Json</returns>
    protected JsonResult MyJson(object data, string format)
    {
      return new CustomJsonResult
      {
        Data = data,
        FormateStr = format
      };
    }

最后我们在自己的Controller中调用即可

public class ProjectMileStoneController : BaseController
  {
    /// <summary>
    /// 首页视图
    /// </summary>
    /// <returns>视图</returns>
    public ActionResult Index()
    {
      return this.View();
    }

    #region 项目里程碑查询

    /// <summary>
    /// 根据项目编号获取项目里程碑
    /// </summary>
    /// <param name="projectId">项目编号</param>
    /// <returns>项目里程碑</returns>
    public JsonResult GetProjectMileStoneByProjectId(int projectId)
    {
      IList<ProjectMileStone> projectMileStones = FacadeContainer.Get<IProjectMileStoneService>().GetProjectMileStonesByProjectId(projectId);
      return this.MyJson(projectMileStones, "yyyy.MM.dd");
    }

    #endregion
  }

原文地址:http://www.cnblogs.com/JerryWang1991

以上就是Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的解决方法,希望对大家的学习有所帮助。

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多