2013年6月19日 星期三

JavaScriptSerializer ScriptIgnoreAttribute

ScriptIgnore這個Attribute是用來取消屬性或欄位的序列化

using System;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = string.Empty;
            Data data = new Data()
            {
                Id = 1,
                Name = "data"
            };

            JavaScriptSerializer jss = new JavaScriptSerializer();
            jsonString = jss.Serialize(data);
            Console.WriteLine(jsonString);
            Console.ReadLine();
        }

        private class Data
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
}

執行結果如下

加上ScriptIgnore這個Attribute之後
using System;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = string.Empty;
            Data data = new Data()
            {
                Id = 1,
                Name = "data"
            };

            JavaScriptSerializer jss = new JavaScriptSerializer();
            jsonString = jss.Serialize(data);
            Console.WriteLine(jsonString);
            Console.ReadLine();
        }

        private class Data
        {
            public int Id { get; set; }

            [ScriptIgnore]
            public string Name { get; set; }
        }
    }
}
執行結果如下