首页 > 代码库 > 【.NET】编程备忘:.Net中的各种序列化

【.NET】编程备忘:.Net中的各种序列化

我们知道将对象的状态保持在存储媒体中,以便可以在以后重新创建精确的副本这正是数据持久化索要做的。而且,不同应用程序之间的通讯需要相互传输数据。那么序列化和反序列化正是为此而生。

序列化和反序列化

所谓序列化就是把对象转换为字节序列的过程称为对象的序列化。

所谓反序列化就是字节序列恢复为对象的过程称为对象的反序列化

那么.net开发中都为我们提供了哪些序列化和反序列化的方式呢?我简单总结了一下,有以下几种:

1.位于System.Xml.Serialization命名空间下的XmlSerializer

2.位于System.Runtime.Serialization.Formatters.Soap命名空间下的SoapFormatter

3.位于System.Runtime.Serialization.Formatters.Binary;命名空间下的BinaryFormatter

4.位于System.Web.Script.Serialization命名空间下的JavaScriptSerializer

5.位于System.Runtime.Serialization.Json命名空间下的DataContractJsonSerializer、DataContractSerializer

4.位于System.Xml.Serialization命名空间下的NetDataContractSerializer

5.来自第三方的Newtonsoft.Json

那么我简单地写了个序列化帮助类。完整代码如下(它们都有各自的使用场合,用法也不止如此):

namespace Serialization{    using System.IO;    using System.Runtime.Serialization;    using System.Runtime.Serialization.Formatters.Binary;    using System.Runtime.Serialization.Formatters.Soap;    using System.Runtime.Serialization.Json;    using System.Text;    using System.Web.Script.Serialization;    using System.Xml.Serialization;    using Newtonsoft.Json;    public class SerializeHelper    {        #region XmlSerializer        public static void XmlSerialize(string fileName, object obj)        {            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))            {                try                {                    XmlSerializer serializer = new XmlSerializer(obj.GetType());                    serializer.Serialize(fs, obj);                }                catch (Exception e)                {                    throw e;                }            }        }        public static T XmlDeSerialize<T>(string fileName) where T : class,new()        {            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                try                {                    XmlSerializer serializer = new XmlSerializer(typeof(T));                    return serializer.Deserialize(fs) as T;                }                catch (Exception e)                {                    throw e;                }            }        }        #endregion        #region SoapFormatter        //不支持泛型 所序列化的类型必须标志为Serializable        public static void SoapSerialize(string fileName, object obj)        {            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))            {                try                {                    SoapFormatter formatter = new SoapFormatter();                    formatter.Serialize(fs, obj);                }                catch (Exception e)                {                    throw e;                }            }        }        public static T SoapDeSerialize<T>(string fileName) where T : class, new()        {            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                try                {                    SoapFormatter formatter = new SoapFormatter();                    return formatter.Deserialize(fs) as T;                }                catch (Exception e)                {                    throw e;                }            }        }        #endregion        #region BinaryFormatter        //所序列化的类型必须标志为Serializable        public static void BinarySerialize(string fileName, object obj)        {            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))            {                try                {                    BinaryFormatter formatter = new BinaryFormatter();                    formatter.Serialize(fs, obj);                }                catch (Exception e)                {                    throw e;                }            }        }        public static T BinaryDeSerialize<T>(string fileName) where T : class, new()        {            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                try                {                    BinaryFormatter formatter = new BinaryFormatter();                    return formatter.Deserialize(fs) as T;                }                catch (Exception e)                {                    throw e;                }            }        }        #endregion        #region JavaScriptSerializer        public static string JavaScriptSerialize(object obj)        {            JavaScriptSerializer serizlizer = new JavaScriptSerializer();            return serizlizer.Serialize(obj);        }        public static T JavaScriptDeSerialize<T>(string json) where T : class, new()        {            JavaScriptSerializer serizlizer = new JavaScriptSerializer();            return serizlizer.Deserialize<T>(json);        }        #endregion        #region DataContractJsonSerializer        /// <summary>        /// (DataContractJsonSerialize)序列化        /// </summary>        /// <param name="item">对象</param>        public static string DataContractJsonSerialize(object obj)        {            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());            using (MemoryStream ms = new MemoryStream())            {                serializer.WriteObject(ms, obj);                return Encoding.UTF8.GetString(ms.ToArray());            }        }        /// <summary>        /// (DataContractJsonSerialize)反序列化        /// </summary>        /// <param name="str">字符串序列</param>        public static T DataContractJsonDeSerialize<T>(string str) where T : class,new()        {            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))            {                return serializer.ReadObject(ms) as T;            }        }        #endregion        #region NetDataContractSerializer        public static void NetDataContractSerialize(string fileName, object obj)        {            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))            {                try                {                    NetDataContractSerializer serializer = new NetDataContractSerializer();                    serializer.Serialize(fs, obj);                }                catch (Exception e)                {                    throw e;                }            }        }        public static T NetDataContractDeSerialize<T>(string fileName) where T : class,new()        {            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                try                {                    NetDataContractSerializer serializer = new NetDataContractSerializer();                    return serializer.Deserialize(fs) as T;                }                catch (Exception e)                {                    throw e;                }            }        }        #endregion        #region DataContractSerializer        public static void DataContractSerialize(string fileName, object obj)        {            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))            {                try                {                    DataContractSerializer serializer = new DataContractSerializer(obj.GetType());                    serializer.WriteObject(fs, obj);                }                catch (Exception e)                {                    throw e;                }            }        }        public static T DataContractDeSerialize<T>(string fileName) where T : class,new()        {            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                try                {                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));                    return serializer.ReadObject(fs) as T;                }                catch (Exception e)                {                    throw e;                }            }        }        #endregion        #region Newtonsoft        public static string JsonConvertSerialize(object item)        {            return JsonConvert.SerializeObject(item);        }        public static T JsonDeSerialize<T>(string json) where T : class,new()        {            return JsonConvert.DeserializeObject<T>(json);        }        #endregion    }}
View Code

 关于各种序列化的各自"用武之地"以及总体性能比较,有空再细细深究。