原文: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

}
}

转载于:https://www.cnblogs.com/lingyun_k/archive/2007/05/01/733778.html

.NET序列化与反序列化(转)相关推荐

  1. [Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...

  2. 序列化和反序列化实现

    1. 什么是序列化? 程序员在编写应用程序的时候往往需要将程序的某些数据存储在内存中,然后将其写入文件或是将其传输到网络中的另一台计算机上以实现通讯.这个将程序数据转换成能被存储并传输的格式的过程被称 ...

  3. Json的序列化和反序列化

    1.引用命名空间: using System.Runtime.Serialization; 2.json的序列化和反序列化的方法: publicclass JsonHelper { ///<su ...

  4. C#实现对象的Xml格式序列化及反序列化

    要序列化的对象的类: [Serializable] public class Person { private string name; public string Name { get { retu ...

  5. c语言xml序列化,C# XML和实体类之间相互转换(序列化和反序列化)

    我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlUtil类,该类来自网络并稍加修改. using System; using System.Collections.Ge ...

  6. 十三、序列化和反序列化(部分转载)

    json和pickle序列化和反序列化 json是用来实现不同程序之间的文件交互,由于不同程序之间需要进行文件信息交互,由于用python写的代码可能要与其他语言写的代码进行数据传输,json支持所有 ...

  7. java培训教程分享:Java中怎样将数据对象序列化和反序列化?

    本期为大家介绍的java培训教程是关于"Java中怎样将数据对象序列化和反序列化?"的内容,相信大家都知道,程序在运行过程中,可能需要将一些数据永久地保存到磁盘上,而数据在Java ...

  8. K:java中的序列化与反序列化

    Java序列化与反序列化是什么?为什么需要序列化与反序列化?如何实现Java序列化与反序列化?以下内容将围绕这些问题进行展开讨论. Java序列化与反序列化 简单来说Java序列化是指把Java对象转 ...

  9. json的序列化与反序列化

    json 是一种轻量级的数据交换格式,也是完全独立于任何程序语言的文本格式. 本文介绍json字符串的序列化与反序列化问题. 序列化 是指将变量(对象)从内存中变成可存储或可传输的过程. 反序列化 是 ...

  10. 深入分析Java的序列化与反序列化

    阅读目录 Java对象的序列化 如何对Java对象进行序列化与反序列化 序列化及反序列化相关知识 ArrayList的序列化 ObjectOutputStream 总结 序列化是一种对象持久化的手段. ...

最新文章

  1. QEMU — Guest Agent
  2. 关系数据库NoSQL数据库
  3. one order callback frequency
  4. 【lora模块技术无线数传电台】E90-DTU产品高防护等级的体现
  5. Linux——umask使用详解
  6. python3 json_python3 json模块
  7. 中国联通董事李福申辞任
  8. VOC2007/2012数据集解析
  9. Grouping BP has not been assigned to any customer accounts groupMessage no. FSBP_ECC004
  10. Linux系统基础命令详细总结,不定期更新,建议收藏
  11. Difference between Vienna DL LLS and UL LLS
  12. rufus安装centos8(旧电脑玩Linux)
  13. [渝粤教育] 西安建筑科技大学 技术经济学 参考 资料
  14. oracle 中的nvl函数使用
  15. RFM分析:如何进行有效的RFM模型搭建和分析?
  16. 12【源码】数据可视化:基于 Echarts +Java SpringBoot 实现的动态实时大屏范例 - 供应链
  17. ZZNU 1995: cots' times
  18. py系统学习笔记:第七阶段:网页编程基础:第二章:CSS3:23.文本、表格属性
  19. substance painter学习1——安装
  20. 计算机培训开班仪式主持词,公文写作培训班主持词

热门文章

  1. [转]隐马尔科夫模型HMM
  2. nodejs/pomelo 使用 mongodb 连接 mongo时 出现
  3. 行人检测资源(上)综述文献
  4. Android 窗口全屏
  5. 关于#include后面和 的区别
  6. 判断URL的HTTP状态
  7. 好的项目需要有好的需求
  8. SQL Server 2008 白皮书
  9. javafx将数据库内容输出到tableview表格
  10. HDFS 命令深入浅出