多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

中國最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2

json教程

  • 關于 JSON
  • JSON 教程

    json格式

    JSON解析

    JSON遍歷

    JSON調用

    JSON轉換

    JSON獲取

    JSON字符串

    JSON數組

    轉換json格式的日期為Javascript對象的函數

    閱讀 (2451)

    項目中碰到了用jQuery從后臺獲取的json格式的日期的字符串,需要將此字符串轉換成JavaScript的日期對象.


    代碼如下:

    //轉換json格式的日期(如:{ServerDatetime:"\/Date(1278930470649)\/"})為Javascript的日期對象 
    function ConvertJSONDateToJSDateObject(JSONDateString) { 
    var date = new Date(parseInt(JSONDateString.replace("/Date(", "").replace(")/", ""), 10)); 
    return date; 



    解決json日期格式問題的3種方法

    開發中有時候需要從服務器端返回json格式的數據,在后臺代碼中如果有DateTime類型的數據使用系統自帶的工具類序列化后將得到一個很長的數字表示日期數據,如下所示:


    代碼如下:

    //設置服務器響應的結果為純文本格式
                context.Response.ContentType = "text/plain";
               //學生對象集合
                List<Student> students = new List<Student>
                {
                    new Student(){Name ="Tom",
                        Birthday =Convert.ToDateTime("2014-01-31 12:12:12")},
                    new Student(){Name ="Rose",
                        Birthday =Convert.ToDateTime("2014-01-10 11:12:12")},
                    new Student(){Name ="Mark",
                        Birthday =Convert.ToDateTime("2014-01-09 10:12:12")}
                };

                //javascript序列化器
                JavaScriptSerializer jss=new JavaScriptSerializer();
               //序列化學生集合對象得到json字符
                string studentsJson=jss.Serialize(students);
               //將字符串響應到客戶端
                context.Response.Write(studentsJson);
               context.Response.End();


    運行結果是:

    js

    其中Tom所對應生日“2014-01-31”變成了1391141532000,這其實是1970 年 1 月 1 日至今的毫秒數;1391141532000/1000/60/60/24/365=44.11年,44+1970=2014年,按這種方法可以得出年月日時分秒和毫秒。這種格式是一種可行的表示形式但不是普通人可以看懂的友好格式,怎么讓這個格式變化?

    解決辦法:

    方法1:在服務器端將日期格式使用Select方法或LINQ表達式轉換后發到客戶端:

    代碼如下:

    using System;
    using System.Collections.Generic;
    using System.Web;

    using System.Web.Script.Serialization;

    namespace JsonDate1
    {
        using System.Linq;

        /// <summary>
        /// 學生類,測試用
        /// </summary>
        public class Student
        {
            /// <summary>
            /// 姓名
            /// </summary>
            public String Name { get; set; }

            /// <summary>
            /// 生日
            /// </summary>
            public DateTime Birthday { get; set; }
        }

        /// <summary>
        /// 返回學生集合的json字符
        /// </summary>
        public class GetJson : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                //設置服務器響應的結果為純文本格式
                context.Response.ContentType = "text/plain";
                //學生對象集合
                List<Student> students = new List<Student>
                {
                    new Student(){Name ="Tom",Birthday =Convert.ToDateTime("2014-01-31 12:12:12")},
                    new Student(){Name ="Rose",Birthday =Convert.ToDateTime("2014-01-10 11:12:12")},
                    new Student(){Name ="Mark",Birthday =Convert.ToDateTime("2014-01-09 10:12:12")}
                };

                //使用Select方法重新投影對象集合將Birthday屬性轉換成一個新的屬性
                //注意屬性變化后要重新命名,并立即執行
                var studentSet =
                    students.Select
                    (
                    p => new { p.Name, Birthday = p.Birthday.ToString("yyyy-mm-dd") }
                    ).ToList();

                //javascript序列化器
                JavaScriptSerializer jss = new JavaScriptSerializer();
                //序列化學生集合對象得到json字符
                string studentsJson = jss.Serialize(studentSet);
                //將字符串響應到客戶端
                context.Response.Write(studentsJson);
                context.Response.End();
            }

            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }


    Select方法重新投影對象集合將Birthday屬性轉換成一個新的屬性,注意屬性變化后要重新命名,屬性名可以相同;這里可以使用select方法也可以使用LINQ查詢表達式,也可以選擇別的方式達到相同的目的;這種辦法可以將集合中客戶端不用的屬性剔除,達到簡單優化性能的目的。 

    運行結果:



    這時候的日期格式就已經變成友好格式了,不過在javascript中這只是一個字符串。

    方法二:

    在javascript中將"Birthday":"\/Date(1391141532000)\/"中的字符串轉換成javascript中的日期對象,可以將Birthday這個Key所對應的Value中的非數字字符以替換的方式刪除,到到一個數字1391141532000,然后實例化一個Date對象,將1391141532000毫秒作為參數,得到一個javascript中的日期對象,代碼如下:


    代碼如下:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>json日期格式處理</title>
        <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function() {
                $.getJSON("getJson.ashx", function (students) {
                    $.each(students, function (index, obj) {
                        $("<li/>").html(obj.Name).appendTo("#ulStudents");

                        //使用正則表達式將生日屬性中的非數字(\D)刪除
                        //并把得到的毫秒數轉換成數字類型
                        var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
                        //實例化一個新的日期格式,使用1970 年 1 月 1 日至今的毫秒數為參數
                        var birthday = new Date(birthdayMilliseconds);

                        $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ;
                    });
                });
            });
        </script>
    </head>
    <body>
        <h2>json日期格式處理</h2>
        <ul id="ulStudents">
        </ul>
    </body>
    </html>

    運行結果:

    日期


    上的使用正則/\D/igm達到替換所有非數字的目的,\D表示非數字,igm是參數,分別表示忽視(ignore)大小寫;多次、全局(global)替換;多行替換(multi-line);有一些時候還會出現+86的情況,只需要變換正則同樣可以達到目的。另外如果項目中反復出現這種需要處理日期格式的問題,可以擴展一個javascript方法,代碼如下:


    代碼如下:

    $(function () {
                $.getJSON("getJson.ashx", function (students) {
                    $.each(students, function (index, obj) {
                      $("<li/>").html(obj.Name).appendTo("#ulStudents");

                      //使用正則表達式將生日屬性中的非數字(\D)刪除
                        //并把得到的毫秒數轉換成數字類型
                        var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, ""));
                      //實例化一個新的日期格式,使用1970 年 1 月 1 日至今的毫秒數為參數
                        var birthday = new Date(birthdayMilliseconds);

                      $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents");
                      $("<li/>").html(obj.Birthday.toDate()).appendTo("#ulStudents");
                    });
                });
            });

            //在String對象中擴展一個toDate方法,可以根據要求完善
            String.prototype.toDate = function () {
                var dateMilliseconds;
                if (isNaN(this)) {
                    //使用正則表達式將日期屬性中的非數字(\D)刪除
                    dateMilliseconds =this.replace(/\D/igm, "");
                } else {
                    dateMilliseconds=this;
                }
                //實例化一個新的日期格式,使用1970 年 1 月 1 日至今的毫秒數為參數
                return new Date(parseInt(dateMilliseconds));
            };

    上面擴展的方法toDate不一定合理,也不夠強大,可以根據需要修改。

    方法三:

    可以選擇一些第三方的json工具類,其中不乏有一些已經對日期格式問題已處理好了的,常見的json序列化與反序列化工具庫有:

    1.fastJSON.
    2.JSON_checker.
    3.Jayrock.
    4.Json.NET - LINQ to JSON.
    5.LitJSON.
    6.JSON for .NET.
    7.JsonFx.
    8.JSONSharp.
    9.JsonExSerializer.
    10.fluent-json
    11.Manatee Json

    這里以litjson為序列化與反序列化json的工具類作示例,代碼如下:


    代碼如下:

    using System;
    using System.Collections.Generic;
    using System.Web;

    using LitJson;

    namespace JsonDate2
    {
        using System.Linq;

        /// <summary>
        /// 學生類,測試用
        /// </summary>
        public class Student
        {
            /// <summary>
            /// 姓名
            /// </summary>
            public String Name { get; set; }

            /// <summary>
            /// 生日
            /// </summary>
            public DateTime Birthday { get; set; }
        }

        /// <summary>
        /// 返回學生集合的json字符
        /// </summary>
        public class GetJson : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                //設置服務器響應的結果為純文本格式
                context.Response.ContentType = "text/plain";
                //學生對象集合
                List<Student> students = new List<Student>
                {
                    new Student(){Name ="Tom",Birthday =Convert.ToDateTime("2014-01-31 12:12:12")},
                    new Student(){Name ="Rose",Birthday =Convert.ToDateTime("2014-01-10 11:12:12")},
                    new Student(){Name ="Mark",Birthday =Convert.ToDateTime("2014-01-09 10:12:12")}
                };

                //序列化學生集合對象得到json字符
                string studentsJson = JsonMapper.ToJson(students);
                //將字符串響應到客戶端
                context.Response.Write(studentsJson);
                context.Response.End();
            }

            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }

    運行結果如下:


    這時候的日期格式就基本正確了,只要在javascript中直接實例化日期就好了,

    var date = new Date("01/31/2014 12:12:12");
    alert(date.toLocaleString());

    客戶端的代碼如下:


    代碼如下:

    $(function () {
                $.getJSON("GetJson2.ashx", function (students) {
                    $.each(students, function (index, obj) {
                        $("<li/>").html(obj.Name).appendTo("#ulStudents");

                        var birthday = new Date(obj.Birthday);
                        $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents");
                    });
                });
            });

            var date = new Date("01/31/2014 12:12:12");
            alert(date.toLocaleString());


    關閉
    程序員人生
    主站蜘蛛池模板: 亚洲欧美在线观看首页 | 高清视频一区二区三区 | 图片区亚洲 | 日本一区二区三区四区五区 | 国产一区二区三区免费 | 国产精品精品视频 | 牛牛精品国内免费一区 | 日本不卡视频在线播放 | 亚洲韩国日本欧美一区二区三区 | 日本一区二区日本免费 | 欧美日韩国产一区二区三区不卡 | 日本japanese18日本护士xxxx | aa一级片| 一区二区三区亚洲视频 | 日本在线视频一区 | 久久精品男人的天堂 | 三级毛片视频 | 亚洲欧洲日韩国产一区二区三区 | 欧美日韩在线视频播放 | 国产人人澡 | 宇都宫紫苑在线播放ed2k | 九月婷婷天天澡天天添天天爽 | 亚洲色图欧美色 | 亚洲无线观看 | 亚洲国产一区二区三区在线观看 | 精品一区二区三区四区五区 | 欧美精品一区二区在线观看 | 精品免费久久久久国产一区 | 在线视频观看一区 | 特级黄aaaaaaaaa毛片 | 女人18毛片a | 图片小说综合 | 欧美成人精品第一区 | 国产激情一区二区三区 | 国内自拍 亚洲系列 欧美系列 | 亚洲国产激情在线一区 | 亚洲午夜久久久精品影院视色 | 亚洲欧美日韩国产综合高清 | 国产91精品久久久久久久 | 欧美亚洲国产精品久久久久 | 欧美另类杂交a |