原文: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. 为什么String中的Java hashCode()使用31作为乘数?
  2. Spring boot的Spring MVC自动配置
  3. LeetCode——Kth Largest Element in an Array
  4. 2.外部链接数据库报错Can't connect to mysql server on xxx.xxx.xxx.xxx(10038)
  5. webService 客户端接口调用【java】
  6. db2取数据库日期时间_DB2数据库取得当前时间的正确解析
  7. android智能电视直播源抓取教程,求人不如求己,教你自己抓取直播源的方法!...
  8. 绝对式编码器的ssi协议 stm32 hal
  9. C实现NV12转I420
  10. mysql表锁ix_S、X、IS、IX数据库锁机制 很详细的教程,简单易懂
  11. cl.b8y.php,群晖如何重装系统
  12. PHP 编写“九九乘法表”
  13. 鼠标悬停,图片向四周放大效果
  14. ecshop手机号码归属地
  15. cc讲故事_停止讲故事
  16. 搭建可以通过外网访问本地服务器CentOS7,这一篇就够了
  17. 【2018-2019】咖啡般的生活,我们互相羡慕着彼此
  18. tmall API接口关键字获取商品数据
  19. SPO 二,SharePoint On-Premises, Online, On Azure.
  20. Oracle特殊字符,转义字符的处理

热门文章

  1. Python学习之路day02——007字典的嵌套
  2. [转]VC工程文件说明
  3. 【转】Prewitt 算子
  4. 不断被刷新的未来——读文档有感
  5. 《深入理解java虚拟机》 - 需要一本书来融汇贯通你的经验(下)
  6. 【备忘】船舶的几个吨位概念
  7. Javassist进行方法插桩
  8. http://jingyan.baidu.com/article/636f38bb3eb78ad6b8461082.html
  9. 2008年国外最佳Web设计/开发技巧、脚本及资源总结
  10. 大公司面试c语言收集(6)