序列化(Serialize)、反序列化(Deserialize)

.NET框架常用的三种序列化的方式:1、是使用IFormatter进行序列化:使用BinaryFormatter(二进制格式)、SoapFormatter(XML格式);2、使用XmlSerializer进行序列化(XML格式),比SoapFormatter的XML格式要简化(去掉了SOAP特有的额外信息)。3、使用DataContractJsonSerializer实现Json格式的序列化和反序列化。


1、使用BinaryFormatter进行串行化

View Code
 1         public string Serialize<T>(T message, IFormatter formatter)
2 {
3 //IFormatter formatter = new BinaryFormatter();
4 //IFormatter formatter = new SoapFormatter();
5 using (MemoryStream stream = new MemoryStream())
6 {
7 formatter.Serialize(stream, message);
8 stream.Position = 0;
9 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
10 {
11 string EncryptMessage = reader.ReadToEnd();
12 return EncryptMessage;
13 }
14 }
15 }
16 public T Deserialize<T>(string encryptMessage, IFormatter formatter)
17 {
18 //IFormatter formatter = new BinaryFormatter();
19 //IFormatter formatter = new SoapFormatter();
20 byte[] buff = Encoding.UTF8.GetBytes(encryptMessage);
21 using (MemoryStream stream = new MemoryStream(buff, 0, buff.Length))
22 {
23 T obj = (T)formatter.Deserialize(stream);
24 return obj;
25 }
26 }

2、使用XmlSerializer进行串行化

    可以使用[Serializable]属性将类标志为可序列化的。如果某个类的元素不想被序列化,1、可以使用[NonSerialized]属性来标志,2、可以使用[XmlIgnore]来标志。

View Code
 1         public string XmlSerialize<T>(T message)
2 {
3 XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
4 using (MemoryStream stream = new MemoryStream())
5 {
6 xmlSerializer.Serialize(stream, message);
7 stream.Position = 0;
8 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
9 {
10 string res = reader.ReadToEnd();
11 return res;
12 }
13 }
14 }
15 public T XmlDeserialize<T>(string encryptMessage)
16 {
17 XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
18 byte[] buff = Encoding.UTF8.GetBytes(encryptMessage);
19 using (MemoryStream stream = new MemoryStream(buff, 0, buff.Length))
20 {
21 T obj = xmlSerializer.Deserialize(stream);
22 return obj;
23 }
24 }


3、使用DataContractJsonSerializer实现Json格式的序列化和反序列化

注意:必须使用DataContractAttribute对类进行标记,使用DataMemberAttribute类成员进行标记,否则该类无法被序列化。

View Code
 1         public string JsonSerialize<T>(T message)
2 {
3 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
4 using (MemoryStream stream = new MemoryStream())
5 {
6 json.WriteObject(stream, message);
7 stream.Position = 0;
8 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
9 {
10 string res = reader.ReadToEnd();
11 return res;
12 }
13 }
14 }
15 public T JsonDeserialize<T>(string message)
16 {
17 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
18 using (MemoryStream stream = new MemoryStream())
19 {
20 T obj = (T)json.ReadObject(stream);
21 return obj;
22 }
23 }

注:.NET Framework 3.5下才可用DataContractJsonSerializer!

你可能感兴趣的:(Serialize)