2013年6月18日 星期二

JavaScriptSerializer 用法

首先開一個Console專案
加入System.Web.Extensions.dll的引用
完整的程式碼如下
using System;
using System.Web.Script.Serialization;

namespace JavaScriptSerializerDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 淮備要序列化的資料
            JsonObject data = new JsonObject()
            {
                ID = 1,
                Name = "JsonObject",
                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}",
                obj.ID,
                obj.Name,
                obj.State,
                obj.Date,
                obj.GUID);

            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": "JsonObject",
  "State": 2,
  "Date": "\/Date(1371484800 000)\/",
  "GUID": "80d39299-a127-459f-b6ef-55626c490f80"
}

執行的結果