【WP7】对象序列化
在WP7中,经常需要使用到保存数据,对对象的保存可以通过序列化到流,然后保存到文件中
常用的有三种序列化方式:xml,Json,DataContract
下面介绍着三种序列化的使用
首先,定义一个序列化类Person
public class Person { public string Name { get; set; } public int Age { get; set; } }
1、使用XmlSerializer序列化
需要引用 System.Xml.Serialization 库
Person person = new Person() { Name = "Bomo", Age = 20 }; //xml序列化开始 MemoryStream ms = new MemoryStream(); XmlSerializer xml = new XmlSerializer(typeof(Person)); xml.Serialize(ms, person);//xml序列化的关键代码 byte[] arr = ms.ToArray(); ms.Close(); string xmlString = Encoding.UTF8.GetString(arr,0,arr.Length); MessageBox.Show(xmlString.Length.ToString()); //xml反序列化 MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)); XmlSerializer xml2 = new XmlSerializer(typeof(Person)); Person pTest = xml.Deserialize(ms2) as Person;//xml反序列化的关键代码 ms2.Close();
2、使用Json
需要引用 System.ServiceModel.Web 库
把对象序列化到流中,然后转换为json字符串
反序列化时,先把字符串读取到流中,然后进行反序列化
Person person = new Person() { Name = "Bomo", Age = 20 }; // 序列化 string jsonString; using (var ms = new MemoryStream()) { new DataContractJsonSerializer(p1.GetType()).WriteObject(ms, p1); jsonString = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length); MessageBox.Show(jsonString.Length.ToString()); } // 反序列化 using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { Person desp = (Person)new DataContractJsonSerializer(typeof(Person)).ReadObject(ms); }
3、使用DataContract序列化
需要引用 System.Runtime.Serialization 库,步骤与Json类似
Person p1 = new Person() { Name = "Bomo", Age = 28 }; //DataContract序列化 MemoryStream ms = new MemoryStream(); DataContractSerializer ser = new DataContractSerializer(typeof(Person)); ser.WriteObject(ms, p1); byte[] array = ms.ToArray(); ms.Close(); string _serializeString = Encoding.UTF8.GetString(array, 0, array.Length); MessageBox.Show(_serializeString.Length.ToString()); //反序列化 DataContractSerializer ser2 = new DataContractSerializer(typeof(Person)); MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(_serializeString)); Person p2 = ser2.ReadObject(ms2) as Person;
以上三种方法,Xml序列化的字符串最大,速度最慢,Json最快,体积最小
推荐使用Json来序列化对象