[.NET]对象序列化与反序列化(Binary,SOAP,XML)操作类封装_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > [.NET]对象序列化与反序列化(Binary,SOAP,XML)操作类封装

[.NET]对象序列化与反序列化(Binary,SOAP,XML)操作类封装

 2013/10/12 17:30:21  YanZhiwei  博客园  我要评论(0)
  • 摘要:SerializationType.cs枚举,表示可以序列化几种类型:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceSerializationHelper{publicenumSerializationType{SOAP,XML,Binary}}SerializationTool.cs抽象类,包括序列化以及反序列化可能用到的方法:usingSystem;usingSystem.Collections
  • 标签:.net net 操作 XML 序列化

SerializationType.cs 枚举,表示可以序列化几种类型:

class="csharpcode">using System;
using System.Collections.Generic;
using System.Text;
namespace SerializationHelper
{
    public enum SerializationType
    {
        SOAP,
        XML,
        Binary
    }
}

SerializationTool.cs 抽象类,包括序列化以及反序列化可能用到的方法:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SerializationHelper
{
    public abstract class SerializationTool
    {
        protected string _path;
        protected virtual void SerializationObject<T>(T t, System.Runtime.Serialization.IFormatter serFormatter)
        {
            try
            {
                if (serFormatter == null)
                    throw new ArgumentNullException("serFormatter");
                using (Stream _stream = new FileStream(_path, FileMode.Create, FileAccess.Write))
                {
                    serFormatter.Serialize(_stream, t);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected virtual void SerializationCollectionToXML<T>(IList<T> collection)
        {
            try
            {
                using (Stream _stream = new FileStream(_path, FileMode.Create, FileAccess.Write))
                {
                    XmlTextWriter _xmlTextWriter = new XmlTextWriter(_stream, new UTF8Encoding(false));
                    _xmlTextWriter.Formatting = Formatting.Indented;
                    XmlSerializer _xmlSerializer = new XmlSerializer(collection.GetType());
                    _xmlSerializer.Serialize(_xmlTextWriter, collection);
                    _xmlTextWriter.Flush();
                    _xmlTextWriter.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected virtual void SerializationObjectToXML<T>(T t)
        {
            try
            {
                using (Stream _stream = new FileStream(_path, FileMode.Create, FileAccess.Write))
                {
                    XmlTextWriter _xmlTextWriter = new XmlTextWriter(_stream, new UTF8Encoding(false));
                    _xmlTextWriter.Formatting = Formatting.Indented;
                    XmlSerializer _xmlSerializer = new XmlSerializer(t.GetType());
                    _xmlSerializer.Serialize(_xmlTextWriter, t);
                    _xmlTextWriter.Flush();
                    _xmlTextWriter.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected virtual T DeSerializationXMLToObject<T>() where T : class
        {
            try
            {
                using (Stream _stream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer _xmlSerializer = new XmlSerializer(typeof(T));
                    return (T)_xmlSerializer.Deserialize(_stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected virtual T DeSerializationObject<T>(IFormatter serFormatter) where T : class
        {
            try
            {
                if (serFormatter == null)
                    throw new ArgumentNullException("SerFormatter");
                using (Stream _stream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                {
                    return (T)serFormatter.Deserialize(_stream);
                }
            }
            catch
            {
                return null;
            }
        }
        public virtual void SerializationCollectionToBinary<T>(IList<T> collection)
        {
            try
            {
                IFormatter _serFormatter = new BinaryFormatter();
                using (Stream _stream = new FileStream(_path, FileMode.Create, FileAccess.Write))
                {
                    _serFormatter.Serialize(_stream, collection);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public virtual IList<T> DeSerializationBinaryToCollection<T>()
        {
            try
            {
                IFormatter _serFormatter = new BinaryFormatter();
                using (Stream _stream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                {
                    return (IList<T>)_serFormatter.Deserialize(_stream);
                }
            }
            catch
            {
                return null;
            }
        }
        protected virtual IList<T> DeSerializationXMLToCollection<T>()
        {
            try
            {
                using (Stream _stream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer _xmlSerializer = new XmlSerializer(typeof(List<T>));
                    return (IList<T>)_xmlSerializer.Deserialize(_stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

ISerializationObjectHelper 接口,定义序列化与反序列化抽象方法:

using System;
using System.Collections.Generic;
using System.Text;

namespace SerializationHelper
{
    public interface ISerializationObjectHelper
    {
        void SerializationObject<T>(T t, SerializationType serializationType);
        T DeSerializationObject<T>(SerializationType serializationType) where T : class;
    }
}

SerializationOperate 密封类,继承SerializationTool, ISerializationObjectHelper:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SerializationHelper
{
    public sealed class SerializationOperate : SerializationTool, ISerializationObjectHelper
    {
        public SerializationOperate(string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path IsNullOrEmpty");
            _path = path;
        }
        #region ISerializationObjectHelper 成员
        public void SerializationObject<T>(T t, SerializationType serializationType)
        {
            switch (serializationType)
            {
                case SerializationType.Binary:
                    SerializationObject<T>(t, new BinaryFormatter());
                    break;
                case SerializationType.SOAP:
                    SerializationObject<T>(t, new SoapFormatter());
                    break;
                case SerializationType.XML:
                    SerializationObjectToXML<T>(t);
                    break;
            }
        }
        public T DeSerializationObject<T>(SerializationType serializationType) where T : class
        {
            T t = null;
            switch (serializationType)
            {
                case SerializationType.Binary:
                    t = DeSerializationObject<T>(new BinaryFormatter());
                    break;
                case SerializationType.SOAP:
                    t = DeSerializationObject<T>(new SoapFormatter());
                    break;
                case SerializationType.XML:
                    t = DeSerializationXMLToObject<T>();
                    break;
            }
            return t;
        }
        #endregion
    }
}

DoSerializableWork 模仿非序列化与反序列化业务逻辑:

    public class DoSerializableWork
    {
        ISerializationObjectHelper _serializableHelper = null;
        public DoSerializableWork(ISerializationObjectHelper serializableHelper)
        {
            if (serializableHelper == null)
                throw new ArgumentNullException("serializableHelper");
            _serializableHelper = serializableHelper;
        }
        public void SerializationObject<T>(T t, SerializationType type)
        {
            _serializableHelper.SerializationObject<T>(t, type);
            Console.WriteLine(string.Format("Serialization {0} to {1} success.", t.GetType().Name, type));
        }
        public void DeSerializationObject(SerializationType type)
        {
            Person _person = _serializableHelper.DeSerializationObject<Person>(type);
            if (_person == null)
            {
                Console.WriteLine(string.Format("DeSerialization {0} to {1} failure.", _person.GetType().Name, type));
            }
            else
            {
                Console.WriteLine(string.Format("Name:{0}\n\rAge:{1}\n\rAddress:{2}\n\rRemark:{3}",
                    _person.Name,
                    _person.Age,
                    _person.Address,
                    _person.Remark));
            }
        }

    }

Person 实体类,需要序列化的实体类:

    [Serializable]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Remark { get; set; }
    }

测试效果:

    class Program
    {
        static void Main(string[] args)
        {
            Person _person = new Person();
            _person.Name = "YanZhiwei";
            _person.Age = 100;
            _person.Address = "Shanghai";
            _person.Remark = ".NET Programmer";
            Person _personNormal = new Person();
            _personNormal.Name = "Normal";
            _personNormal.Age = 100;
            _personNormal.Address = "Shanghai";
            _personNormal.Remark = "Normal";
            IList<Person> _persons = new List<Person>();
            _persons.Add(_person);
            _persons.Add(_personNormal);
            try
            {
                DoSerializableWork _doSerializableWorkToBinary = new DoSerializableWork(
                    new SerializationOperate(string.Format(@"C:\{0}SerializableTest.bin", DateTime.Now.ToString("yyyyMMddHH"))));
                _doSerializableWorkToBinary.SerializationObject(_person, SerializationType.Binary);
                _doSerializableWorkToBinary.DeSerializationObject(SerializationType.Binary);
                Console.WriteLine("-----------------------------------------");

                DoSerializableWork _doSerializableWorkToSoap = new DoSerializableWork(
                    new SerializationOperate(string.Format(@"C:\{0}SerializableTest.soap", DateTime.Now.ToString("yyyyMMddHH"))));
                _doSerializableWorkToSoap.SerializationObject(_person, SerializationType.SOAP);
                _doSerializableWorkToSoap.DeSerializationObject(SerializationType.SOAP);
                Console.WriteLine("-----------------------------------------");

                DoSerializableWork _doSerializableWorkToXML = new DoSerializableWork(
                    new SerializationOperate(string.Format(@"C:\{0}SerializableTest.xml", DateTime.Now.ToString("yyyyMMddHH"))));
                _doSerializableWorkToXML.SerializationObject(_person, SerializationType.XML);
                _doSerializableWorkToXML.DeSerializationObject(SerializationType.XML);
                Console.WriteLine("-----------------------------------------");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.Trim());
            }
        }
    }

image

image

image

image

image

发表评论
用户名: 匿名