码迷,mamicode.com
首页 > Web开发 > 详细

ASP.MVC时间类型json数据处理

时间:2016-11-29 17:13:16      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:并且   文件   row   append   new   json   .ajax   erro   format   

      服务端返回DateTime属性如果用自带的json方法返回的数据如下:

技术分享

1.辅助各文件

 public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }


        [HttpGet]
        /// <summary>
        /// 得到数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetData()
        {
            List<TestData> getList = new List<TestData>()
            {
                new TestData()
                {
                     TestId=1,
                      TestTime=DateTime.Now
                },
                new TestData()
                {
                    TestId=2,
                    TestTime=DateTime.Now.AddDays(2)
                }
            };
            return this.Json(getList,JsonRequestBehavior.AllowGet);
        }
    }

    public class TestData
    {
        public int TestId { get; set; }

        public DateTime TestTime { get; set; }
    }
@{
    ViewBag.Title = "Index";
    Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
    var result = new Object();
    $.ajax({
        url: /Home/GetData,
        type: get,
        dataType: json,
        success: function (r) {
            debugger;
            result = r;

        },
        complete: function () {
            debugger;
        },
        error: function (a, b, c) {
            debugger
        }

    })
</script>

2.创建一个基类控制器,并且写一个MVC->JsonResult的子类

  public class BaseController : Controller
    {
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new ToJsonResult
            {
                Data = data,
                ContentEncoding = contentEncoding,
                ContentType = contentType,
                JsonRequestBehavior = behavior,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };
        }
    }
 /// <summary>
    /// 说明:转化为Jason
    /// 作者: CallmeYhz
    /// </summary>
    public class ToJsonResult : JsonResult
    {
        const string error = "该请求已被封锁,因为敏感信息透露给第三方网站,这是一个GET请求时使用的。为了可以GET请求,请设置JsonRequestBehavior AllowGet。";
        /// <summary>
        /// 格式化字符串
        /// </summary>
        public string FormateStr
        {
            get;
            set;
        }

        /// <summary>
        /// 说明:重写ExecueResult方法
        /// 作者:CallmeYhz    
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(error);
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonstring = serializer.Serialize(Data);


                //string hashOldPassword = @"\\/Date\((\param+)\+\param+\)\\/";

                string p = @"\\/Date\(\d+\)\\/";

                MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);

                Regex reg = new Regex(p);

                jsonstring = reg.Replace(jsonstring, matchEvaluator);
                response.Write(jsonstring);
            }
        }

        /// <summary>
        /// 说明:将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// 作者:CallmeYhz   
        /// </summary>
        private string ConvertJsonDateToDateString(Match m)
        {

            string result = string.Empty;

            string p = @"\d";
            var cArray = m.Value.ToCharArray();
            StringBuilder sb = new StringBuilder();

            Regex reg = new Regex(p);
            for (int i = 0; i < cArray.Length; i++)
            {
                if (reg.IsMatch(cArray[i].ToString()))
                {
                    sb.Append(cArray[i]);
                }
            }
            // reg.Replace(m.Value;

            DateTime dt = new DateTime(1970, 1, 1);

            dt = dt.AddMilliseconds(long.Parse(sb.ToString()));

            dt = dt.ToLocalTime();

            result = dt.ToString(this.FormateStr);

            return result;
        }
    }

3.继承

技术分享

4.输出结果

 技术分享

 

ASP.MVC时间类型json数据处理

标签:并且   文件   row   append   new   json   .ajax   erro   format   

原文地址:http://www.cnblogs.com/CallmeYhz/p/6114156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!