主页 > 知识库 > 解决Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的方法

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

热门标签:硅谷的囚徒呼叫中心 电子围栏 苹果 呼叫中心 地方门户网站 智能手机 服务器配置 解决方案

问题背景:

           在使用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)
    {
      IListProjectMileStone> projectMileStones = FacadeContainer.GetIProjectMileStoneService>().GetProjectMileStonesByProjectId(projectId);
      return this.MyJson(projectMileStones, "yyyy.MM.dd");
    }

    #endregion
  }

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

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

您可能感兴趣的文章:
  • python使用json序列化datetime类型实例解析
  • JS实现将Asp.Net的DateTime Json类型转换为标准时间的方法
  • 让python json encode datetime类型
  • 关于fastjson的@JSONField注解的一些问题(详解)
  • SpringMVC restful 注解之@RequestBody进行json与object转换
  • java JSONArray 遍历方式(2种)
  • SQL Server之JSON 函数详解
  • JsonFormat与@DateTimeFormat注解实例解析

标签:佳木斯 玉林 德宏 海口 喀什 泰安 吕梁 房产

巨人网络通讯声明:本文标题《解决Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的方法》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266