资源描述:
《课题序列化与反序列化及Json序列化反序列化.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、序列化与反序列化,及Json序列化反序列化序列化是将对象状态转换为可保持或可传输的格式的过程,反序列化则过程相反。用于存储和传输数据。(一)asp.net序列化与反序列化.net提供多种序列化类(1)BinaryFormatter 类名字空间:System.Runtime.Serialization.Formatters.Binary这个类用于以二进制格式将对象或整个连接对象图形序列化和反序列化构造器两个:BinaryFormatter()BinaryFormatter(ISurrogateSelector, Str
2、eamingContext) 介绍它的两个主要方法:1Serialize方法将对象或连接对象图形序列化为给定流它有两个重载:Serialize(Stream, Object)Serialize(Stream, Object,Header[]) 类Customerpublic class Customer{ public int Unid { get; set; } public string Name { get; set; } public string Call { get; set; }} 下
3、边通过示例来测试序列化方法Serializepublic void TestSerialize(){ Customer customer = new Customer {Unid=1,Name="宋江",Call="" }; FileStream fs = new FileStream("test.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); try { formatt
4、er.Serialize(fs, customer); } catch { } finally { fs.Close(); }} 测试时,这个会抛出异常:类型“SerializeTest.Customer”未标记为可序列化。所以要在Customer类上添加修饰标签[Serializable]public class Customer 测试,在bindebug文件夹中可以看到test.dat文件。2Deserialize方法将流反序列化为对象图形,它也有两个重载Des
5、erialize(Stream) Deserialize(Stream, HeaderHandler) 通过示例来测试从流进行反序列化 public void TestDeserialize(){ Customer customer = new Customer(); FileStream fs = new FileStream("test.dat", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); cust
6、omer= formatter.Deserialize(fs) as Customer; fs.Close(); Console.WriteLine(customer.Name);} 结果输出:宋江(2)SoapFormatter类名字空间:System.Runtime.Serialization.Formatters.Soap以 SOAP 格式将对象或整个连接对象的图形序列化和反序列化。SOAP就是simpleobjectaccessprotocol的缩写,简单对象传输协议。是一种轻量的,简单的,基于x
7、ml的协议。这个要添加对System.Runtime.Serialization.Formatters.Soap.dll的引用构造器:SoapFormatter xx=new SoapFormatter()SoapFormatter(ISurrogateSelector, StreamingContext) 主要介绍其中2个方法1 Serialize方法Serialize(Stream, Object) Serialize(Stream, Object, Header[] public void TestSoapS
8、erialize(){ Customer customer = new Customer { Unid = 1, Name = "宋江", Call = "" }; FileStream fs = new FileStream("soaptest.dat", FileMode.Create); SoapFormatter fo