序列化和反序列化我们可能经常会听到,其实通俗一点的解释,序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的时候把这个文件再转化成原来的对象使用。
我想最主要的作用有:
1、在进程下次启动时读取上次保存的对象的信息
2、在不同的AppDomain或进程之间传递数据
3、在分布式应用系统中传递数据
......
在C#中常见的序列化的方法主要也有三个:BinaryFormatter、SoapFormatter、XML序列化
本文就通过一个小例子主要说说这三种方法的具体使用和异同点
这个例子就是使用三种不同的方式把一个Book对象进行序列化和反序列化,当然这个Book类首先是可以被序列化的。
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->using System;
using System.Collections;
using System.Text;
namespace SerializableTest
{
[Serializable]
public class Book
{
public Book()
{
alBookReader = new ArrayList();
}
public string strBookName;
[NonSerialized]
public string strBookPwd;
private string _bookID;
public string BookID
{
get { return _bookID; }
set { _bookID = value; }
}
public ArrayList alBookReader;
private string _bookPrice;
public void SetBookPrice(string price)
{
_bookPrice = price;
}
public void Write()
{
Console.WriteLine("Book ID:" + BookID);
Console.WriteLine("Book Name:" + strBookName);
Console.WriteLine("Book Password:" + strBookPwd);
Console.WriteLine("Book Price:" + _bookPrice);
Console.WriteLine("Book Reader:");
for (int i = 0; i < alBookReader.Count; i++)
{
Console.WriteLine(alBookReader[i]);
}
}
}
}
这个类比较简单,就是定义了一些public字段和一个可读写的属性,一个private字段,一个标记为[NonSerialized]的字段,具体会在下面的例子中体现出来
一、BinaryFormatter序列化方式
1、序列化,就是给Book类赋值,然后进行序列化到一个文件中
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> Book book = new Book();
book.BookID = " 1 " ;
book.alBookReader.Add( " gspring " );
book.alBookReader.Add( " 永春 " );
book.strBookName = " C#强化 " ;
book.strBookPwd = " ***** " ;
book.SetBookPrice( " 50.00 " );
BinarySerialize serialize = new BinarySerialize();
serialize.Serialize(book);
2、反序列化
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> BinarySerialize serialize = new BinarySerialize();
Book book = serialize.DeSerialize();
book.Write();
3、测试用的
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializableTest
{
public class BinarySerialize
{
string strFile = "c://book.data";
public void Serialize(Book book)
{
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, book);
}
}
public Book DeSerialize()
{
Book book;
using (FileStream fs = new FileStream(strFile, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
book = (Book)formatter.Deserialize(fs);
}
return book;
}
}
}
主要就是调用System.Runtime.Serialization.Formatters.Binary空间下的BinaryFormatter类进行序列化和反序列化,以缩略型二进制格式写到一个文件中去,速度比较快,而且写入后的文件已二进制保存有一定的保密效果。
调用反序列化后的截图如下:
也就是说除了标记为NonSerialized的其他所有成员都能序列化
二、SoapFormatter序列化方式
调用序列化和反序列化的方法和上面比较类似,我就不列出来了,主要就看看SoapSerialize类
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
namespace SerializableTest
{
public class SoapSerialize
{
string strFile = "c://book.soap";
public void Serialize(Book book)
{
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(fs, book);
}
}
public Book DeSerialize()
{
Book book;
using (FileStream fs = new FileStream(strFile, FileMode.Open))
{
SoapFormatter formatter = new SoapFormatter();
book = (Book)formatter.Deserialize(fs);
}
return book;
}
}
}
主要就是调用System.Runtime.Serialization.Formatters.Soap空间下的SoapFormatter类进行序列化和反序列化,使用之前需要应用System.Runtime.Serialization.Formatters.Soap.dll(.net自带的)
序列化之后的文件是Soap格式的文件(简单对象访问协议(Simple Object Access Protocol,SOAP),是一种轻量的、简单的、基于XML的协议,它被设计成在WEB上交换结构化的和固化的信息。 SOAP 可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议(HTTP),简单邮件传输协议(SMTP),多用途网际邮件扩充协议(MIME)。它还支持从消息系统到远程过程调用(RPC)等大量的应用程序。SOAP使用基于XML的数据结构和超文本传输协议(HTTP)的组合定义了一个标准的方法来使用Internet上各种不同操作环境中的分布式对象。)
调用反序列化之后的结果和方法一相同
三、XML序列化方式
调用序列化和反序列化的方法和上面比较类似,我就不列出来了,主要就看看XmlSerialize类
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace SerializableTest
{
public class XmlSerialize
{
string strFile = "c://book.xml";
public void Serialize(Book book)
{
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
XmlSerializer formatter = new XmlSerializer(typeof(Book));
formatter.Serialize(fs, book);
}
}
public Book DeSerialize()
{
Book book;
using (FileStream fs = new FileStream(strFile, FileMode.Open))
{
XmlSerializer formatter = new XmlSerializer(typeof(Book));
book = (Book)formatter.Deserialize(fs);
}
return book;
}
}
}
从这三个测试类我们可以看出来其实三种方法的调用方式都差不多,只是具体使用的类不同
xml序列化之后的文件就是一般的一个xml文件:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--><?xml version="1.0"?>
<Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<strBookName>C#强化</strBookName>
<strBookPwd>*****</strBookPwd>
<alBookReader>
<anyType xsi:type="xsd:string">gspring</anyType>
<anyType xsi:type="xsd:string">永春</anyType>
</alBookReader>
<BookID>1</BookID>
</Book>
输出截图如下:
也就是说采用xml序列化的方式只能保存public的字段和可读写的属性,对于private等类型的字段不能进行序列化
另外,还可以使用XmlArrayAttribute和XmlArrayItemAttribute来XML序列化数组,
XmlArrayAttribute指定数组元素的Xml节点名,XmlArrayItemAttribute指定数组元素的Xml节点名。
请参考下面的示例:[XmlRoot("cats")]
public class CatCollection
{
[XmlArray("items"),XmlArrayItem("item")]
public Cat[] Cats { get; set; }
}
[XmlRoot("cat")]
public class Cat
{
//定义Color属性的序列化为cat节点的属性
[XmlAttribute("color")]
public string Color { get; set; }
//要求不序列化Speed属性
[XmlIgnore]
public int Speed { get; set; }
//设置Saying属性序列化为Xml子元素
[XmlElement("saying")]
public string Saying { get; set; }
}
输出的结果:
<?xml version="1.0" encoding="gb2312"?>
<cats xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://ww
w.w3.org/2001/XMLSchema">
<items>
<item color="White">
<saying>White or black, so long as the cat can catch mice, it is a good
cat</saying>
</item>
<item color="Black">
<saying>White or black, so long as the cat can catch mice, it is a good
cat</saying>
</item>
</items>
</cats>
关于XmlSerializer内存泄露的问题。
MSDN上的描述为:
为了提高性能,XML 序列化基础结构将动态生成程序集,以序列化和反序列化指定类型。此基础结构将查找并重复使用这些程序集。此行为仅在使用以下构造函数时发生:
如果使用任何其他构造函数,则会生成同一程序集的多个版本,且绝不会被卸载,这将导致内存泄漏和性能降低。最简单的解决方案是使用先前提到的两个构造函数的其中一个。否则,必须在Hashtable 中缓存程序集
也就是说我们在使用XmlSerializer序列化,初始化XmlSerializer对象时最好使用下面两个构造函数否则会引起内存泄漏。
XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)
关于循环引用:
比如在上面的例子Book类中加入如下一个属性:
public Book relationBook;
在调用序列化时使用如下方法:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> Book book = new Book();
book.BookID = " 1 " ;
book.alBookReader.Add( " gspring " );
book.alBookReader.Add( " 永春 " );
book.strBookName = " C#强化 " ;
book.strBookPwd = " ***** " ;
book.SetBookPrice( " 50.00 " );
Book book2 = new Book();
book2.BookID = " 2 " ;
book2.alBookReader.Add( " gspring " );
book2.alBookReader.Add( " 永春 " );
book2.strBookName = " .NET强化 " ;
book2.strBookPwd = " ***** " ;
book2.SetBookPrice( " 40.00 " );
book.relationBook = book2;
book2.relationBook = book;
BinarySerialize serialize = new BinarySerialize();
serialize.Serialize(book);
这样就会出现循环引用的情况,对于BinarySerialize和SoapSerialize可以正常序列化(.NET内部进行处理了),对于XmlSerialize出现这种情况会报错:"序列化类型 SerializableTest.Book 的对象时检测到循环引用。"
.Net中序列化和反序列化JSON的代码:
public class Weather
{
public WeatherInfo weatherinfo { get; set; }
}
public class WeatherInfo
{
public string city { get; set; }
public string date_y { get; set; }
public string date { get; set; }
public string week { get; set; }
public string temp1 { get; set; }
public string temp2 { get; set; }
public string temp3 { get; set; }
public string weather1 { get; set; }
public string weather2 { get; set; }
public string weather3 { get; set; }
public string img_title1 { get; set; }
public string img_title2 { get; set; }
public string img_title3 { get; set; }
public string wind1 { get; set; }
public string wind2 { get; set; }
public string wind3 { get; set; }
public string index_d { get; set; }
public string index_xc { get; set; }
public string index_cl { get; set; }
}
public class JsonHelper
{
/// <summary>
/// JSON序列化
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = null;
string jsonString = null;
try
{
ms = new MemoryStream();
ser.WriteObject(ms, t);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
}
finally
{
if (ms != null)
{
ms.Close();
ms = null;
}
}
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = null;
T obj = default(T);
try
{
ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
obj = (T)ser.ReadObject(ms);
}
finally
{
if (ms != null)
{
ms.Close();
ms = null;
}
}
return obj;
}
}
别忘了引用dll: System.ServiceModel.Web, System.Runtime.Serialization
调用的例子:
Weather wi = JsonHelper.JsonDeserialize<Weather>(text);
Console.WriteLine(wi.weatherinfo.city);