C# JavaScriptSerializer 自定义序列化

虽然,我个人建议使用Json.Net。

但大家需求不同。遇到一个朋友,他有个需求JavaScriptSerializer并且序列化时,隐藏基类成员。

这里我采用自定义序列化来实现:

public static void Main(string[] args)
        {
            MyException my = new MyException();
            my.Code = 200;
            my.Message = "hello";
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.RegisterConverters(new JavaScriptConverter[] { new MyJSConverter() });
            var q = jss.Serialize(my);
 
            var v = jss.Deserialize<MyException>(q);
 
            Console.ReadLine();
        }
 
 
        public class MyException : Exception
        {
            public int Code = -1;
            public new string Message = "";
            public new List<MyException> InnerException = new List<MyException> { };
        }
 
        public class MyJSConverter : JavaScriptConverter
        {
 
            public override IEnumerable<Type> SupportedTypes
            {
                //Define the ListItemCollection as a supported type.
                get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(MyException) })); }
            }
 
            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {
                MyException entity = obj as MyException;
 
                if (entity != null)
                {
                    // Create the representation.
                    Dictionary<string, object> result = new Dictionary<string, object>();
                    result.Add("Code", entity.Code);
                    result.Add("Message", entity.Message);
 
                    return result;
                }
                return new Dictionary<string, object>();
            }
 
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                if (dictionary == null)
                    throw new ArgumentNullException("dictionary");
 
                if (type == typeof(MyException))
                {
                    MyException my = new MyException();
                    my.Code = (int)dictionary["Code"];
                    my.Message = (string)dictionary["Message"];
                    return my;
                }
                return null;
            }
 
        }

效果:

原文地址:https://www.cnblogs.com/hanjun0612/p/11775562.html