zoukankan      html  css  js  c++  java
  • .NET序列化与反序列化(转)

    原文:http://dotnet.mblogger.cn/cuijiazhao/posts/3400.aspx

    .net提供了三种序列化方式:

    1.XML Serialize

    2.Soap Serialize

    3.Binary Serialize

    第一种序列化方式对有些类型不能够序列化,如hashtable;我主要介绍后两种类型得序列化

    一.Soap Serialize

    使用SoapFormatter.Serialize()实现序列化.SoapFamatter在System.Runtime.Serialization.Formatters.Soap命名空间下,使用时需要引用System.Runtime.Serialization.Formatters.Soap.dll.它可将对象序列化成xml.

    [Serializable]
      public class Option:ISerializable
      {
    //此构造函数必须实现,在反序列化时被调用.
       public Option(SerializationInfo si, StreamingContext context)
       {
        this._name=si.GetString("NAME");
        this._text=si.GetString("TEXT");
        this._att =(MeteorAttributeCollection)si.GetValue("ATT_COLL",typeof(MeteorAttributeCollection));
       }
       public Option(){_att = new MeteorAttributeCollection();}
       public Option(string name,string text,MeteorAttributeCollection att)
       {
        _name = name;
        _text = text;
        _att = (att == null ? new MeteorAttributeCollection():att);
       }
       private string _name;
       private string _text;
       private MeteorAttributeCollection _att;
       /// <summary>
       /// 此节点名称
       /// </summary>
       public String Name
       {
        get{return this._name;}
        set{this._name =value;}
       }
       /// <summary>
       /// 此节点文本值
       /// </summary>
       public String Text
       {
        get{return this._text;}
        set{this._text =value;}
       }
       /// <summary>
       /// 此节点属性
       /// </summary>
       public MeteorAttributeCollection AttributeList
       {
        get{return this._att;}
        set{this._att=value;}
       }
    ///此方法必须被实现
       public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
       {
        info.AddValue("NAME",this._name);
        info.AddValue("TEXT",this._text);
        info.AddValue("ATT_COLL",this._att,typeof(MeteorAttributeCollection));
       }
    }
    在这个类中,红色部分为必须实现的地方.否则在序列化此类的时候会产生异常“必须被标注为可序列化“,“未找到反序列化类型Option类型对象的构造函数“等异常

    *****************************

    下面是序列化与反序列化类 MeteorSerializer.cs

    ************************

    using System;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Soap;
    using System.Runtime.Serialization.Formatters.Binary;

    namespace Maxplatform.Grid
    {
     /// <summary>
     /// 提供多种序列化对象的方法(SoapSerializer,BinarySerializer)
     /// </summary>
     public class MeteorSerializer
     {
      public MeteorSerializer()
      {
      
      }
     
      #region Soap
      /// <summary>
      /// Soap格式的序列化
      /// </summary>
      /// <param name="o"></param>
      /// <returns></returns>
      public static string SoapSerializer(object o)
      {
       // To serialize the hashtable and its key/value pairs, 
       // you must first open a stream for writing.
       // In this case, use a file stream.
       //FileStream fs = new FileStream("DataFile.xml", FileMode.Create);
       Stream ms=new MemoryStream();
       // Construct a BinaryFormatter and use it to serialize the data to the stream.
       SoapFormatter formatter = new SoapFormatter();
       try
       {
        formatter.Serialize(ms, o);
      
        byte[] b=new byte[ms.Length];
        ms.Position=0;
        ms.Read(b,0,b.Length);
                   
        string s=Convert.ToBase64String(b);
        return s;
       }
       catch (SerializationException e)
       {
        //Log.Write("ServiceNode:Exception","Failed to serialize. Reason: " + e.Message);
        throw e;
       }
       finally
       {
        ms.Close();
       }

      }
      /// <summary>
      /// Soap格式的反序列化
      /// </summary>
      /// <param name="returnString"></param>
      /// <returns></returns>
      public static object SoapDeserialize(string returnString)
      {

       // Open the file containing the data that you want to deserialize.
       SoapFormatter formatter;
       MemoryStream ms=null;
       try
       {
        formatter = new SoapFormatter();

        byte[] b=Convert.FromBase64String(returnString);

        ms=new MemoryStream(b);
       
        // Deserialize the hashtable from the file and
        // assign the reference to the local variable.
        object o = formatter.Deserialize(ms);
        return o;
       }
       catch (SerializationException e)
       {
        //Log.Write("ServiceNode:Exception","Failed to deserialize. Reason: " + e.Message);
        throw e;
       }
       finally
       {
        ms.Close();
       
       }

      }
      #endregion

      #region Binary
      /// <summary>
      /// Binary格式的序列化
      /// </summary>
      /// <param name="o"></param>
      /// <returns></returns>
      public static string BinarySerializer(object o)
      {
       // To serialize the hashtable and its key/value pairs, 
       // you must first open a stream for writing.
       // In this case, use a file stream.
       //FileStream fs = new FileStream("DataFile.xml", FileMode.Create);
       Stream ms=new MemoryStream();
       // Construct a BinaryFormatter and use it to serialize the data to the stream.
       BinaryFormatter formatter = new BinaryFormatter();
       try
       {
        formatter.Serialize(ms, o);
      
        byte[] b=new byte[ms.Length];
        ms.Position=0;
        ms.Read(b,0,b.Length);
                   
        string s=Convert.ToBase64String(b);
        return s;
       }
       catch (SerializationException e)
       {
        //Log.Write("ServiceNode:Exception","Failed to serialize. Reason: " + e.Message);
        throw e ;
       }
       finally
       {
        ms.Close();
       }

      }
      /// <summary>
      /// Binary格式的反序列化
      /// </summary>
      /// <param name="returnString"></param>
      /// <returns></returns>
      public static object BinaryDeserialize(string returnString)
      {

       // Open the file containing the data that you want to deserialize.
       BinaryFormatter formatter;
       MemoryStream ms=null;
       try
       {
        formatter = new BinaryFormatter();

        byte[] b=Convert.FromBase64String(returnString);

        ms=new MemoryStream(b);
       
        // Deserialize the hashtable from the file and
        // assign the reference to the local variable.
        object response = formatter.Deserialize(ms);
        return response;
       }
       catch (SerializationException e)
       {
        //Log.Write("ServiceNode:Exception","Failed to deserialize. Reason: " + e.Message);
        throw e;
       }
       finally
       {
        ms.Close();
       
       }

      }
      #endregion

     

     }
    }

  • 相关阅读:
    使用python在SAE上搭建一个微信应用,使用有道翻译的api进行在线翻译
    使用python一步一步搭建微信公众平台(一)
    Socket 多线程FTP软件开发
    (转)SQL NEWID()随机函数
    (转)ip地址,手机ip查询
    (转)webservice 测试窗体只能用于来自本地计算机的请求
    (转)WITH (NOLOCK)
    (转)jquery.url.js 插件的使用
    (转)SQL中的ISNULL函数介绍
    (转) C# Activator.CreateInstance()方法使用
  • 原文地址:https://www.cnblogs.com/lingyun_k/p/733778.html
Copyright © 2011-2022 走看看