序列化就是把一个对象变成流的形式,方便传输和还原。小弟不才,总结下对二进制序列化和Json序列化的使用:
1.首先,二进制序列化(BinaryFormatter)要求要序列化的类必须是可序列化的(即在类定义的前面加Serializable关键字),而且它的父类类型也必须是可序列化的,经过查看发现,Dotnet中很多类型和结构都有这个标记;而Json序列化不用写标记;
2.如果类中某些属性不希望被二进制序列化,加NonSerialized关键字即可,而要二进制序列化的属性的类型必须是可序列化的数据类型;
3.二进制序列化只会对类中的字段(属性)序列化,故序列化时不建议使用自动属性(每次生成的字段都可能不一样,影响反序列化)。
下面是二进制序列化的代码:
1.要序列化的类的定义:
1 [Serializable]
2 public class Person
3 {
4 private string _sName;
5
6 public string SName
7 {
8 get { return _sName; }
9 set { _sName = value; }
10 }
11
12 private int _iAge;
13
14 public int IAge
15 {
16 get { return _iAge; }
17 set { _iAge = value; }
18 }
19
20 private string _sEmail;
21
22 public string SEmail
23 {
24 get { return _sEmail; }
25 set { _sEmail = value; }
26 }
27
28 private string _sPhone;
29
30 public string SPhone
31 {
32 get { return _sPhone; }
33 set { _sPhone = value; }
34 }
35
36 private string _sAddress;
37
38 public string SAddress
39 {
40 get { return _sAddress; }
41 set { _sAddress = value; }
42 }
43
44 private string _sSex;
45
46 public string SSex
47 {
48 get { return _sSex; }
49 set { _sSex = value; }
50 }
51
52 private Car _myCar;
53
54 public Car MyCar
55 {
56 get { return _myCar; }
57 set { _myCar = value; }
58 }
59
60 public Person()
61 {
62
63 }
64
65 public Person(string name,int age,string sex,string email,string phone,string address,Car car):this()
66 {
67 this.SName = name;
68 this.IAge = age;
69 this.SSex = sex;
70 this.SEmail = email;
71 this.SPhone = phone;
72 this.SAddress = address;
73 this.MyCar = car;
74 }
75 }
76 [Serializable]
77 public class Car
78 {
79 private string _sCarType;
80
81 public string SCarType
82 {
83 get { return _sCarType; }
84 set { _sCarType = value; }
85 }
86
87 private string _sCarNum;
88
89 public string SCarNum
90 {
91 get { return _sCarNum; }
92 set { _sCarNum = value; }
93 }
94
95 public Car()
96 {
97
98 }
99
100 public Car(string carType,string carNum):this()
101 {
102 this.SCarType = carType;
103 this.SCarNum = carNum;
104 }
105 }
View Code
2.二进制序列化代码:
BinaryFormatter bf = new BinaryFormatter();
Person p = null;
using (FileStream fsWrite=new FileStream("person.bin",FileMode.Create,FileAccess.Write))
{
if (ckbIsCar.Checked)
{
var strCarNum = txtCarNum.Text.Trim();
var strCarType = txtCarType.Text.Trim();
Car c1=new Car(strCarType,strCarNum);
p = new Person(strName, intAge,strSex, strEmail, strPhone, strAddress, c1);
}
else
{
//不登记车的情况
p = new Person(strName, intAge,strSex, strEmail, strPhone, strAddress, null);
}
//二进制序列化
bf.Serialize(fsWrite, p);
MessageBox.Show("对象序列化完毕");
View Code
在进行二进制反序列化(还原对象时),需要将序列化程序集中的.exe和.pdb两个文件拷贝进来,并添加对程序集的引用,二进制反序列化很简单,代码如下:
1 BinaryFormatter bf = new BinaryFormatter();
2 string strPath = ConfigurationManager.AppSettings["FilePath"];
3 StringBuilder sb = new StringBuilder();
4
5 using (FileStream fsRead=new FileStream(strPath,FileMode.Open,FileAccess.Read))
6 {
7 Person p1 = bf.Deserialize(fsRead) as Person;
8 if (p1!=null)
9 {
10 Car c1 = p1.MyCar;
11 if (c1!=null)
12 {
13 //登记了车的信息
14 sb.AppendFormat("姓名:{0};\r\n年龄:{1}岁;\r\n性别:{2};\r\n联系电话:{3};\r\n电子邮箱:{4};\r\n联系地址:{5};\r\n车型:{6};\r\n车牌号:{7}。", p1.SName, p1.IAge, p1.SSex, p1.SPhone, p1.SEmail, p1.SAddress, c1.SCarType, c1.SCarNum);
15 }
16 else
17 {
18 sb.AppendFormat("姓名:{0};\r\n年龄:{1}岁;\r\n性别:{2};\r\n联系电话:{3};\r\n电子邮箱:{4};\r\n联系地址:{5}。", p1.SName, p1.IAge, p1.SSex, p1.SPhone, p1.SEmail, p1.SAddress);
19 }
20 }
21 }
22 lbResult.Text = sb.ToString();
View Code
再来说说Json序列化,先上代码:
1 Console.WriteLine("请输入您的姓名:");
2 string sName = Console.ReadLine();
3 if (!string.IsNullOrEmpty(sName))
4 {
5 Console.WriteLine("{0},请输入你的年龄:",sName);
6 int iAge = int.Parse(Console.ReadLine());
7 Console.WriteLine("{0},请输入你的性别:",sName);
8 string sSex = Console.ReadLine();
9 Console.WriteLine("{0},请输入你的E-Mail地址:",sName);
10 string sEmail = Console.ReadLine();
11 Console.WriteLine("{0},请输入你的联系电话:",sName);
12 string sPhone = Console.ReadLine();
13 Console.WriteLine("{0},请输入你的通信地址:",sName);
14 string sAddress = Console.ReadLine();
15
16 Person p = new Person(sName, iAge, sSex, sEmail, sPhone, sAddress);
17 JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
18 //执行Json序列化
19 File.WriteAllText("demo.txt", jsSerializer.Serialize(p));
20 Console.WriteLine("Json序列化完毕");
View Code
Json序列化好的数据是一对大括号括起来的,每个数据由属性名和值中间加个“:”组成。
Json反序列化一样很简单,同理,也需要将序列化程序集中的.exe和.pdb两个文件拷贝进来,并添加对程序集的引用,代码如下:
Json反序列化
1 string sPath = ConfigurationManager.AppSettings["FilePath"];
2 string sContent = File.ReadAllText(sPath, Encoding.UTF8);
3
4 JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
5 //这里使用泛型方法可以避免类型转换,方便使用!
6 Person p1 = jsSerializer.Deserialize<Person>(sContent);
7 Console.WriteLine("姓名:" + p1.SName);
8 Console.WriteLine("性别:"+p1.SSex);
9 Console.WriteLine("年龄:"+p1.IAge.ToString());
10 Console.WriteLine("联系电话:"+p1.SPhone);
11 Console.WriteLine("E-mail:"+p1.SEmail);
12 Console.WriteLine("联系地址:"+p1.SAddress);
13 Console.ReadKey();
View Code
最后说一下今天我在做Json序列化时,遇到的一个问题:在写出类名JavaScriptSerializer后怎么都无法引用(类名也不会变蓝色),在网上查了下,终于找到方法(我用的是Visual Studio 2010,2012也不行):
首先在项目上右击“属性”,如果目标框架是:.net framework 4 Client profile的,自然引用不了,要改成正式版,即选不带后缀(不带Client profile的),更改后项目中自然多了一个app.config项目配置文件,再引用System.web.Extensions这个程序集。问题即可解决。