2013年6月18日 星期二

JavaScriptSerializer 轉換 IDictionary 介面

一樣開個新的Console專案,和加入System.Web.Extensions.dll參考
完整的程式碼如下
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace JavaScriptSerializerDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 淮備要序列化的資料
            Dictionary<string, object> data = new Dictionary<string, object>()
            {
                {
                    "ID", 1
                },
                {
                    "Name", "Dictionary Demo"
                },
                {
                    "State", EnumState.c
                },
                {
                    "Date", DateTime.Today
                },
                {
                    "Guid", Guid.NewGuid()
                }
            };

            // 序列化
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string jsonString = jss.Serialize(data);
            Console.WriteLine("序列化的JSON字串:{0}\r\n", jsonString);

            // 反序列化
            JsonObject obj = jss.Deserialize<JsonObject>(jsonString);
            Console.WriteLine(
                "反序列化後的物件, ID:{0}, Name:{1}, State:{2}, Date:{3}, GUID:{4}\r\n",
                obj.ID,
                obj.Name,
                obj.State,
                obj.Date,
                obj.GUID);

            
            Dictionary<string, object> dict = jss.Deserialize<Dictionary<string, object>>(jsonString);
            Console.WriteLine("反序列化回Dictionary");
            foreach (var key in dict.Keys)
            {
                Console.WriteLine("Key:{0}, Value:{1}", key, dict[key]);
            }

            Console.ReadLine();
        }

        /// <summary>
        /// 要序列化的資料類別
        /// </summary>
        private class JsonObject
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public EnumState State { get; set; }
            public DateTime Date { get; set; }
            public Guid GUID { get; set; }
        }

        /// <summary>
        /// 狀態列舉
        /// </summary>
        public enum EnumState
        {
            a = 0,
            b = 1,
            c = 2
        }
    }
}


序列化後的JSON
{
  "ID": 1,
  "Name": "Dictionary Demo",
  "State": 2,
  "Date": "\/Date(13714 84800000)\/",
  "Guid": "7c52f0a4-a742-4898-a55c-583ab851b183"
}

輸出的結果