• 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;
                }
     
            }

    效果:

  • 相关阅读:
    beta阶段贡献分配实施
    Beta发布
    Beta发布——视频博客
    Scrum立会报告+燃尽图(Beta阶段第二周第七次)
    Beta发布——美工+文案
    Scrum立会报告+燃尽图(Beta阶段第二周第六次)
    Scrum立会报告+燃尽图(Beta阶段第二周第五次)
    Scrum立会报告+燃尽图(Beta阶段第二周第四次)
    Scrum立会报告+燃尽图(Beta阶段第二周第三次)
    20181011-1每周例行报告
  • 原文地址:https://www.cnblogs.com/hanjun0612/p/11775562.html
Copyright © 2020-2023  润新知