序列化/反序列化

关于序列化与反序列化的知识,对于现在的C#程序员来说并不是什么新的东西了。今天我就大概说一下比较常用而序列化与序列化的通用方法。

一:概念

将对象的状态信息转换为可以存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。[引用百科]

二:目的

持久化存储、按值封送

三:特点

A:数据传输快。因为它可以把一个对象序列化成字节流,流在两台服务器之间传输是比较快的。

B:易于保存。序列化的结果体积比较小,例如:序列化成二进制格式存储的。可以保存成一个文件,或是存储到数据库

C:安全性高,你可以把一个明文的对象,进行序列化。再用自己的加密算法进行加密。即使别人看到了,也无法知道其中的内容

D:跨平台:XML序列化是可以跨平台的。因为序列化的XML是标准的XML文档

四:我们开始代码吧

(1)Binary序列化器

命名空间:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

复制代码
 1    /// <summary>
 2         /// 序列化
 3         /// </summary>
 4         /// <typeparam name="T">要序列化的对象类型</typeparam>
 5         /// <param name="file">序列化出来的文件</param>
 6         /// <param name="tObj">要序列化的对象</param>
 7         /// <returns></returns>
 8         public static string Serialize<T>(T obj)
 9         {
10             using (MemoryStream stream = new MemoryStream())
11             {
12                 IFormatter formatter = new BinaryFormatter();
13                 formatter.Serialize(stream, obj);
14                 return stream.ToString();
15             }
16         }
17         /// <summary>
18         /// 反序列化
19         /// </summary>
20         /// <typeparam name="T">反序列化出来对象类型</typeparam>
21         /// <param name="file">要反序列化的文件</param>
22         /// <returns></returns>
23        public static T Deserialize<T>(string objContent)
24         {
25             T obj = default(T);
26             using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(objContent)))
27             {
28                 IFormatter formatter = new BinaryFormatter();
29                 obj = (T)formatter.Deserialize(stream);
30                 return obj;
31 
32             }
33         }
复制代码

(2)XML序列化器
命名空间

using System.IO;

using System.Xml;
using System.Xml.Serialization;

复制代码
 1       /// <summary>
 2        /// 序列化
 3        /// </summary>
 4        /// <typeparam name="T">要序列化的对象类型</typeparam>
 5        /// <param name="file">序列化出来的文件</param>
 6        /// <param name="tObj">要序列化的对象</param>
 7        /// <returns></returns>
 8        public static string SerializeXML<T>(T obj)
 9        {
10            XmlSerializer xs = new XmlSerializer(typeof(T));
11            using (MemoryStream ms = new MemoryStream())
12            {
13                xs.Serialize(ms, obj);
14                ms.Seek(0, SeekOrigin.Begin);
15 
16                byte[] buffer = new byte[ms.Length];
17                int n = ms.Read(buffer, 0, buffer.Length);
18                ms.Close();
19                return System.Text.Encoding.UTF8.GetString(buffer, 0, n);
20            }
21        }
22        /// <summary>
23        /// 反序列化
24        /// </summary>
25        /// <typeparam name="T">反序列化出来对象类型</typeparam>
26        /// <param name="file">要反序列化的文件</param>
27        /// <returns></returns>
28        public static T DeserializeXML<T>(string objContent)
29        {
30            using (MemoryStream ms = new MemoryStream())
31            {
32                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objContent);
33                ms.Write(buffer, 0, buffer.Length);
34                ms.Seek(0, SeekOrigin.Begin);
35                XmlSerializer xs = new XmlSerializer(typeof(T));
36                T mc = (T)xs.Deserialize(ms);
37                ms.Close();
38                return mc;
39            }
40           
41        }
复制代码

(3)SOAP序列化
命名空间

using System.Runtime.Serialization.Formatters.Soap;
using System.IO;

复制代码
 1   public static string SerializeSoap<T>(T obj)
 2         {
 3             SoapFormatter format = new SoapFormatter();
 4             using (MemoryStream ms = new MemoryStream())
 5             {
 6                 format.Serialize(ms, obj);
 7                 ms.Seek(0, SeekOrigin.Begin);
 8 
 9                 byte[] buffer = new byte[ms.Length];
10                 int n = ms.Read(buffer, 0, buffer.Length);
11                 ms.Close();
12                 return System.Text.Encoding.UTF8.GetString(buffer, 0, n);
13             }
14         }
15 
16         public static T DeSerializeSoap<T>(string objContent)
17         {
18             using (MemoryStream ms = new MemoryStream())
19             {
20                 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objContent);
21                 ms.Write(buffer, 0, buffer.Length);
22                 ms.Seek(0, SeekOrigin.Begin);
23                 SoapFormatter xs = new SoapFormatter();
24 
25                 T mc = (T)xs.Deserialize(ms);
26                 ms.Close();
27                 return mc;
28             }
29         }
复制代码

 

 

(4)JSON序列化

命名空间

using System.IO;

using System.Runtime.Serialization.Json;

.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用

复制代码
 1   /// <summary>
 2        /// JSON序列化
 3        /// </summary>
 4        public static string JsonSerializer<T>(T t)
 5        {
 6            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
 7            MemoryStream ms = new MemoryStream();
 8            ser.WriteObject(ms, t);
 9            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
10            ms.Close();
11            return jsonString;
12        }
13 
14        /// <summary>
15        /// JSON反序列化
16        /// </summary>
17        public static T JsonDeserialize<T>(string jsonString)
18        {
19            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
20            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
21            T obj = (T)ser.ReadObject(ms);
22            return obj;
23        }
复制代码

整理完毕。通用只是一种说法。可能在数据格式特殊时会有一定的错误。得通过自己去调整额外代码解决了。

posted @ 2012-06-14 15:22  Aaron.Wu  阅读(189)  评论(0编辑  收藏  举报