类对象序列化操作类

记录下类对象序列化的类以便以后用到

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

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

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

namespace TTOCR.Common
{
    /// <summary>
    /// 类对象序列化操作类
    /// </summary>
    public static class ClassObjectSerializerHelper
    {
        #region 对象序列化为byte数组
        /// <summary>
        /// 对象序列化为byte数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static byte[] Serialize_Byte<T>(T t)
        {
            MemoryStream mStream = new MemoryStream();
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(mStream, t);
            return mStream.GetBuffer();
        }
        #endregion 对象序列化为byte数组

        #region byte数组序列化为对象
        /// <summary>
        /// byte数组序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="b"></param>
        /// <returns></returns>
        public static T Deserialize_Byte<T>(byte[] b)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            return (T)bFormatter.Deserialize(new MemoryStream(b));
        }
        #endregion byte数组序列化为对象


        #region 对象序列化为XML格式串
        /// <summary>
        /// 对象序列化为XML格式串
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer_XMLString(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            //创建序列化对象
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }

            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();
            return str;
        }
        #endregion 对象序列化为XML格式串

        #region 对象序列化为XML格式串
        /// <summary>
        /// 对象序列化为XML格式串
        /// </summary>
        /// <param name="type"></param>
        /// <param name="obj"></param>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static bool Serializer_XMLString(Type type, object obj, string xmlPath)
        {
            bool rsbool = false;

            try
            {
                FileStream fs = new FileStream(xmlPath, FileMode.Create);

                //添加开头的<?xml version="1.0" encoding="utf-8"?>
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = Encoding.UTF8;  //指定编码
                settings.Indent = true;             //是否换行缩进

                using (XmlWriter writer = XmlWriter.Create(fs, settings))
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    //ns.Add("", ""); //去除默认命名空间xmlns:xsd和xmlns:xsi,则使用ns.Add("","");                     
                    XmlSerializer xmlSerializer = new XmlSerializer(type);
                    xmlSerializer.Serialize(writer, obj, ns);
                }

                fs.Close();
                rsbool = true;
            }
            catch (Exception ex)
            {
                Log.LogErr("对象序列化为XML格式串时出错,xmlPath:" + xmlPath + "; errormsg:" + ex.Message);
                //OnMessage(MSGCODE.ERROR, "MetadataHelper.cs>MetadataSerializer(...)[将SIP对象序列化XML对象]异常: " + ex.Message);
                rsbool = false;
            }

            return rsbool;
        }
        #endregion 对象序列化为XML格式串

        #region XML格式串反序列化为对象
        /// <summary>
        /// XML格式串反序列化为对象
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize_XMLString(Type type, string xml)
        {
            //try
            //{
            using (StringReader sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(type);
                return xmldes.Deserialize(sr);
            }
            //}
            //catch (Exception e)
            //{
            //    return null;
            //}
        }
        #endregion XML格式串反序列化为对象

        #region 将XML文件反序列化为对象
        /// <summary>
        /// 将XML文件反序列化为对象
        /// <param name="xmlPath">xml路径</param>
        /// <param name="type"></param>
        /// <returns></returns>
        /// </summary>
        public static object DeSerializer_XmlFile(string xmlPath, Type type)
        {
            try
            {
                FileStream file = new FileStream(xmlPath, FileMode.Open, FileAccess.Read);
                XmlSerializer xmlSearializer = new XmlSerializer(type);

                object obj = xmlSearializer.Deserialize(file);
                file.Close();
                return obj;
            }
            catch (Exception ex)
            {
                Log.LogErr("将XML文件反序列化为对象时出错,xmlPath:" + xmlPath + "; errormsg:" + ex.Message);
                //OnMessage(MSGCODE.ERROR, "MetadataHelper.cs>MetadataDeSerializer(...)[将XML对象反序列化为SIP对象]异常: " + ex.Message);
                return null;
            }
        }
        #endregion 将XML文件反序列化为对象


        #region 对象序列化为Json格式串
        /// <summary>
        /// 对象序列化为Json格式串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer_JsonString(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }
        #endregion 对象序列化为Json格式串

        #region 对象序列化为Json格式串(其它重载方法)
        public static string Serializer_JsonString(object obj, Newtonsoft.Json.Formatting formatting)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, formatting);
        }

        public static string Serializer_JsonString(object obj, Newtonsoft.Json.JsonSerializerSettings settings)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, settings);
        }

        public static string Serializer_JsonString(object obj, params Newtonsoft.Json.JsonConverter[] converters)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, converters);
        }

        public static string Serializer_JsonString(object obj, Newtonsoft.Json.Formatting formatting, Newtonsoft.Json.JsonSerializerSettings settings)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, formatting, settings);
        }

        public static string Serializer_JsonString(object obj, Newtonsoft.Json.Formatting formatting, params Newtonsoft.Json.JsonConverter[] converters)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, formatting, converters);
        }

        public static string Serializer_JsonString(object obj, Type type, Newtonsoft.Json.JsonSerializerSettings settings)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, type, settings);
        }
        public static string Serializer_JsonString(object obj, Type type, Newtonsoft.Json.Formatting formatting, Newtonsoft.Json.JsonSerializerSettings settings)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, type, formatting, settings);
        }
        #endregion 对象序列化为Json格式串(其它重载方法)


        #region Json格式串反序列化为对象
        /// <summary>
        /// Json格式串反序列化为对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="str">json格式的字符串</param>
        /// <returns></returns>
        public static T Deserialize_JsonString<T>(string str)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }
        #endregion Json格式串反序列化为对象

        #region Dictionary类序列化为XML
        ///// <summary>
        ///// Dictionary类序列化为XML
        ///// </summary>
        ///// <param name="rootName">根元素名称</param>
        ///// <param name="dicObj">Dictionary对象</param>
        //public static string Serializer_XmlString_Dictionary(string rootName, Dictionary<string, object> dicObj)
        //{
        //    string xmlStr = "";

        //    //将录入的数据信息动态构造成一个数据对象类
        //    //动态类名称
        //    string DynamicClassName = rootName;//"DynamicClass";

        //    //动态创建类属性
        //    Dictionary<string, string> propertyInfo = new Dictionary<string, string>();
        //    foreach (string key in dicObj.Keys)
        //    {
        //        propertyInfo.Add(key, "string");//propertyInfo.Add(fieldName, "object");
        //    }

        //    System.Reflection.Assembly assembly = DynamicClass.NewAssembly(DynamicClassName, propertyInfo);
        //    object objClass = assembly.CreateInstance(DynamicClassName);

        //    //设置属性值::遍历所有控件,找到每个控件的FieldValue
        //    foreach (string key in dicObj.Keys)
        //    {
        //        //获取到每个控件的FieldName和FieldValue                
        //        DynamicClass.ReflectionSetProperty(objClass, key, dicObj[key]);
        //    }

        //    //序列化对象
        //    xmlStr = ClassObjectSerializerHelper.Serializer_XMLString(objClass.GetType(), objClass);
        //    //string UIDataSet_JsonStr = ClassObjectSerializerHelper.Serializer_JsonString(objClass);

        //    return xmlStr;
        //}
        #endregion Dictionary类序列化为XML

        #region Dictionary类序列化为XML
        ///// <summary>
        ///// Dictionary类序列化为XML
        ///// </summary>
        ///// <param name="rootName">根元素名称</param>
        ///// <param name="dicObj">Dictionary对象</param>
        ///// <param name="xmlPath">XML文件存储路径</param>
        //public static bool Serializer_XmlString_Dictionary(string rootName, Dictionary<string, object> dicObj, string xmlPath)
        //{
        //    bool rsBool = false;

        //    //将录入的数据信息动态构造成一个数据对象类
        //    //动态类名称
        //    string DynamicClassName = rootName;//"DynamicClass";

        //    //动态创建类属性
        //    Dictionary<string, string> propertyInfo = new Dictionary<string, string>();
        //    foreach (string key in dicObj.Keys)
        //    {
        //        propertyInfo.Add(key, "string");//propertyInfo.Add(fieldName, "object");
        //    }

        //    System.Reflection.Assembly assembly = DynamicClass.NewAssembly(DynamicClassName, propertyInfo);
        //    object objClass = assembly.CreateInstance(DynamicClassName);

        //    //设置属性值::遍历所有控件,找到每个控件的FieldValue
        //    foreach (string key in dicObj.Keys)
        //    {
        //        //获取到每个控件的FieldName和FieldValue                
        //        DynamicClass.ReflectionSetProperty(objClass, key, dicObj[key]);
        //    }

        //    //序列化对象,并存储            
        //    ClassObjectSerializerHelper.Serializer_XMLString(objClass.GetType(), objClass, xmlPath);

        //    rsBool = true;

        //    return rsBool;
        //}
        #endregion Dictionary类序列化为XML



    }
}

 

posted @ 2016-05-24 11:11  三小  阅读(1974)  评论(0编辑  收藏  举报