C# 实现复杂对象的序列化与反序列化
      (注:本篇文章是本人根据msdn,各位同行的心得再加上自己对序列化的一些想法汇集而成,如有不当,还请指教)
     
    序列化是将对象转换为容易传输的格式的过程。例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象。反之,反序列化根据流重新构造对象。这里主要介绍两种序列的方法:一是XML 序列化,二是Binary序列化。
         1.   XML序列
            XML 序列化仅将对象的公共字段和属性值序列化为 XML 流。XML 序列化不包括类型信息。例如,如果 Library 命名空间中有一个 Book 对象,将不能保证它会被反序列化为同一类型的对象。XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 
   
         首先,声明两个用来序列的对象,一个用户设置对象和一个图层参数对象,用户设置对象包括了用户信息和一个图层列表:
 /// <summary>
/// <summary>2
 /// 图层参数
    /// 图层参数3
 /// </summary>
    /// </summary>4
 [Serializable]
    [Serializable]5
 public class LayerPara
    public class LayerPara6
 {
    {7
 public int ID;
        public int ID;8
 public string MC;               // 中文名称
        public string MC;               // 中文名称9
 public string Layer;            // 数据集名称
        public string Layer;            // 数据集名称10
 public short GBCode;            // 分类码
        public short GBCode;            // 分类码11
 public short GeoType;           // 图层对应的几何类型, 11表示点图层,12表示线图层
        public short GeoType;           // 图层对应的几何类型, 11表示点图层,12表示线图层12
 public int MinScale;            // 显示的最小比例尺
        public int MinScale;            // 显示的最小比例尺13
 }
    }14
 [Serializable]
    [Serializable]15
 public class UserSetting
    public class UserSetting16
 {
    {17
 public string strUserName = "kandy";
        public string strUserName = "kandy";18
 public string strUserPwd = "123456789";
        public string strUserPwd = "123456789";19
 public List<LayerPara> userLayerParas;
        public List<LayerPara> userLayerParas;20
 }
    }21

     然后,声明一个进行序列与反序列的类,其中WriteDataToFile实现将文件写如本地指定的路径,ReadDataFormFile方法实现将文件从磁盘中读取:
 class Serialize
class Serialize {
    { 
         public List<UserSetting> m_LayerParamsList;
        public List<UserSetting> m_LayerParamsList; public UserSetting userSetting;
        public UserSetting userSetting; public Serialize()
        public Serialize() {
        { this.ResetLayersInfo();
            this.ResetLayersInfo(); this.WriteDataToFile(userSetting);
            this.WriteDataToFile(userSetting); }
        }
 private void ResetLayersInfo()
        private void ResetLayersInfo() {
        { m_LayerParamsList = new List<UserSetting>();
            m_LayerParamsList = new List<UserSetting>();
 userSetting = new UserSetting();
            userSetting = new UserSetting(); userSetting.userLayerParas = new List<LayerPara>();
            userSetting.userLayerParas = new List<LayerPara>(); 
            
 LayerPara layerPara = new LayerPara();
            LayerPara layerPara = new LayerPara(); layerPara.ID = 100;
            layerPara.ID = 100; layerPara.MC = "管点";
            layerPara.MC = "管点"; layerPara.Layer = "gd";
            layerPara.Layer = "gd"; layerPara.GBCode = 4;
            layerPara.GBCode = 4; layerPara.GeoType = 5;
            layerPara.GeoType = 5; layerPara.MinScale = 100;
            layerPara.MinScale = 100;
 userSetting.userLayerParas.Add(layerPara);
            userSetting.userLayerParas.Add(layerPara); 
            layerPara = new LayerPara();
 layerPara.ID = 200;
            layerPara.ID = 200; layerPara.MC = "管线";
            layerPara.MC = "管线"; layerPara.Layer = "gx";
            layerPara.Layer = "gx"; layerPara.GBCode = 5;
            layerPara.GBCode = 5; layerPara.GeoType = 6;
            layerPara.GeoType = 6; layerPara.MinScale = 100;
            layerPara.MinScale = 100;
 userSetting.userLayerParas.Add(layerPara);
            userSetting.userLayerParas.Add(layerPara); 
            }
        }
 private void WriteDataToFile(UserSetting tempUserSetting)
        private void WriteDataToFile(UserSetting tempUserSetting) {
        { if (tempUserSetting != null)
            if (tempUserSetting != null) {
            { try
                try {
                { string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
                    string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory; strSaveToPath = strSaveToPath + "UserLayerSetting.xml";
                    strSaveToPath = strSaveToPath + "UserLayerSetting.xml"; Stream stream = new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    Stream stream = new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlSerializer xmlFormatter = new XmlSerializer(typeof(UserSetting));
                    XmlSerializer xmlFormatter = new XmlSerializer(typeof(UserSetting)); xmlFormatter.Serialize(stream, tempUserSetting);
                    xmlFormatter.Serialize(stream, tempUserSetting); stream.Close();
                    stream.Close();
 Console.WriteLine(" serialize is finished!");
                    Console.WriteLine(" serialize is finished!"); }
                } catch (InvalidOperationException e)
                catch (InvalidOperationException e) {
                { Console.WriteLine(e.Message);
                    Console.WriteLine(e.Message); }
                } }
            } }
        }
 public UserSetting ReadDataFormFile()
        public UserSetting ReadDataFormFile() {
        { UserSetting setting = new UserSetting();
            UserSetting setting = new UserSetting(); string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
            string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory; strSaveToPath = strSaveToPath + "UserLayerSetting.xml";
            strSaveToPath = strSaveToPath + "UserLayerSetting.xml";
 bool isExist = this.IsExsitFileInAppPath(strSaveToPath);
            bool isExist = this.IsExsitFileInAppPath(strSaveToPath); if (isExist)
            if (isExist) {
            { Stream stream = new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                Stream stream = new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); XmlSerializer formatter = new XmlSerializer(typeof(UserSetting));
                XmlSerializer formatter = new XmlSerializer(typeof(UserSetting)); try
                try {
                { setting = (UserSetting)formatter.Deserialize(stream);
                    setting = (UserSetting)formatter.Deserialize(stream); Console.WriteLine(setting.strUserName);
                    Console.WriteLine(setting.strUserName); Console.WriteLine(setting.strUserPwd);
                    Console.WriteLine(setting.strUserPwd); foreach(LayerPara lp in setting.userLayerParas)
                    foreach(LayerPara lp in setting.userLayerParas) {
                    { Console.WriteLine(lp.ID.ToString());
                        Console.WriteLine(lp.ID.ToString()); Console.WriteLine(lp.MC);
                        Console.WriteLine(lp.MC); Console.WriteLine(lp.Layer);
                        Console.WriteLine(lp.Layer); Console.WriteLine(lp.GBCode.ToString());
                        Console.WriteLine(lp.GBCode.ToString()); Console.WriteLine(lp.GeoType.ToString());
                        Console.WriteLine(lp.GeoType.ToString()); Console.WriteLine(lp.MinScale);
                        Console.WriteLine(lp.MinScale); Console.WriteLine("\n");
                        Console.WriteLine("\n"); }
                    } }
                } catch (SerializationException e)
                catch (SerializationException e) {
                { Console.WriteLine(e.Message);
                    Console.WriteLine(e.Message); }
                } }
            } else
            else Console.WriteLine("File is not Exist!");
                Console.WriteLine("File is not Exist!");
 return setting;
            return setting; }
        }
 private bool IsExsitFileInAppPath(string strTempPath)
        private bool IsExsitFileInAppPath(string strTempPath) {
        { bool bExsit = false;
            bool bExsit = false; bExsit = File.Exists(strTempPath);
            bExsit = File.Exists(strTempPath); return bExsit;
            return bExsit; }
        } 
         }
    }
现在我们就可以在Main()方法中进行调用了,下面是一个进行测试的类,包含了主程序的Main()方法:
 public class Testing
public class Testing {
    { public static void Main()
        public static void Main() {
        { Console.WriteLine("Serialize is beginning");
            Console.WriteLine("Serialize is beginning");
 Serialize serialize = new Serialize();
            Serialize serialize = new Serialize(); serialize.ReadDataFormFile();
            serialize.ReadDataFormFile(); Console.WriteLine("Read have finished!");
            Console.WriteLine("Read have finished!"); Console.Read();
            Console.Read(); 
             }
        } }
    }
   2.Binary序列
      这里主要谈的是BinaryFormatter,它位于System.Runtime.Serialization.Formatters.Binary名字空间下,以二进制格式将对象或整个连接对象图形序列化和反序列化。个人认为BinaryFormatter比第一种方法更好用,它同样也有Serialize和DeSerialize方法,具体代码我就贴序列与反序列的代码了,其原理与过程都大致相同,下面是序列与反序列的代码:
 private void SaveLayerToAppPath(List<LayerPara> tempLayerParas)
private void SaveLayerToAppPath(List<LayerPara> tempLayerParas) {
        { if (tempLayerParas != null)
            if (tempLayerParas != null) {
            { string strSaveToPath=AppDomain.CurrentDomain.BaseDirectory;
                string strSaveToPath=AppDomain.CurrentDomain.BaseDirectory; strSaveToPath=strSaveToPath+"layer.dat";
                strSaveToPath=strSaveToPath+"layer.dat"; Stream stream = new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.None);
                Stream stream = new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.None); IFormatter formatter = new BinaryFormatter();
                IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, tempLayerParas);
                formatter.Serialize(stream, tempLayerParas); stream.Close();
                stream.Close();
 Console.WriteLine(" serialize is success!");
                Console.WriteLine(" serialize is success!"); }
            } }
        }
 public List<LayerPara> ReadDataFormFile()
        public List<LayerPara> ReadDataFormFile() {
        { List<LayerPara> tempLayerPara = new List<LayerPara>();
            List<LayerPara> tempLayerPara = new List<LayerPara>();
 string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
            string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory; strSaveToPath = strSaveToPath + "layer.dat";
            strSaveToPath = strSaveToPath + "layer.dat";
 bool isExist = this.IsExsitFileInAppPath(strSaveToPath);
            bool isExist = this.IsExsitFileInAppPath(strSaveToPath); if (isExist)
            if (isExist) {
            { Stream stream = new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.None);
                Stream stream = new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.None); BinaryFormatter formatter = new BinaryFormatter();
                BinaryFormatter formatter = new BinaryFormatter();
 try
                try {
                { tempLayerPara = (List<LayerPara>)formatter.Deserialize(stream);
                    tempLayerPara = (List<LayerPara>)formatter.Deserialize(stream); foreach (LayerPara lp in tempLayerPara)
                    foreach (LayerPara lp in tempLayerPara) {
                    { Console.WriteLine(lp.ID.ToString());
                        Console.WriteLine(lp.ID.ToString()); Console.WriteLine(lp.MC);
                        Console.WriteLine(lp.MC); Console.WriteLine(lp.Layer);
                        Console.WriteLine(lp.Layer); Console.WriteLine(lp.GBCode.ToString());
                        Console.WriteLine(lp.GBCode.ToString()); Console.WriteLine(lp.GeoType.ToString());
                        Console.WriteLine(lp.GeoType.ToString()); Console.WriteLine(lp.MinScale);
                        Console.WriteLine(lp.MinScale); }
                    } }
                } catch (SerializationException e)
                catch (SerializationException e) {
                { Console.WriteLine(e.Message);
                    Console.WriteLine(e.Message); }
                } }
            } else
            else Console.WriteLine("File is not Exist!");
                Console.WriteLine("File is not Exist!");
 return tempLayerPara;
            return tempLayerPara; }
        }   总结:主要是根据的实际项目需要了,看你适合哪种方法.
 
                    
                     
                    
                 
                    
                

 
         
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号