一、序列化和反序列化的概念
序列化:序列化是将对象转换为可保持或传输的格式的过程,比如转化为二进制、xml、json等的过程。
反序列化:与序列化相对的是反序列化,它将流转换为对象,也就是将在序列化过程中所生成的二进制串、xml、json等转换成数据结构或者对象的过程。
二、序列化和反序列化的作用
1、在不同的AppDomain或进程之间传递数据
比喻说现在有一个java写的应用要向C#写的应用进行通信,传递数据,那么这个时候java将要传的数据进行序列化,C#应用接收数据后进行反序列化。
2、在进程下次启动时读取上次保存的对象的信息
三、序列化的三个方法
1、BinaryFormatter
用法大致如下:
//BinaryFormatter将对象序列化到文件中
List<string> inputList = new List<string>() { "百度","https://www.baidu.com/","百度一下,你就知道"};
using (FileStream fsWriter = new FileStream(@"gz168168.tmp",FileMode.Create,FileAccess.Write))
{
BinaryFormatter bf = new BinaryFormatter();
//序列化
bf.Serialize(fsWriter, inputList);
}
//BinaryFormatter将文件中的数据反序列化出来
List<string> outputList = new List<string>();
using (FileStream fsReader = new FileStream(@"gz168168.tmp",FileMode.Open,FileAccess.Read))
{
BinaryFormatter bf = new BinaryFormatter();
//反序列化
outputList = (List<string>)bf.Deserialize(fsReader);
}
2、XML序列化
用法大致如下:
//xml序列化到 test.xml文件中
List<string> inputList = new List<string>() { "百度一下","https://www.baidu.com/"};
using (FileStream fsWriter = new FileStream(@"test.xml",FileMode.Create,FileAccess.Write))
{
XmlSerializer xs = new XmlSerializer(typeof(List<string>));
xs.Serialize(fsWriter, inputList);
}
//从test.xml文件中反序列化出来
List<string> outputList = new List<string>();
using (FileStream fsReader = new FileStream(@"test.xml",FileMode.Open,FileAccess.Read))
{
XmlSerializer xs = new XmlSerializer(typeof(List<string>));
outputList = xs.Deserialize(fsReader) as List<string>;
}
3、json序列化
使用JSON.NET类库
List<Student> lstStuModel = new List<Student>()
{
new Student(){ID=1,Name="吕布",Age=25,Sex="男"},
new Student(){ID=2,Name="貂蝉",Age=22,Sex="女"}
};
//Json.NET序列化
string jsonData = JsonConvert.SerializeObject(lstStuModel);
Console.WriteLine(jsonData);
Console.ReadKey();
//Json.NET反序列化
string json = @"{'Name':'C#','Age':'30','ID':'1','Sex':'女'}";
Student descJsonStu = JsonConvert.DeserializeObject<Student>(json);//反序列化
Console.WriteLine(string.Format("反序列化:ID={0},Name={1},Sex={2},Sex={3}",descJsonStu.ID,descJsonStu.Name,descJsonStu.Age,descJsonStu.Sex));
Console.ReadKey();