天天看點

.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

 }

}

繼續閱讀