C#byte[]序列化及xml序列化,支持序列化后再压缩.

/// 
    /// 对象的序列化助手
    /// 
    public static class SerializerHelper
    {
        /// 
        /// 返回对象序列化为byte数组
        /// 
        /// 对象类型
        /// 对象
        /// 
        public static byte[] GetByteSerialize(T t)
        {
            return GetByteSerialize(t, true);
        }
        public static byte[] GetDataMemberSerialize(T t)
            where T:IList
        {
            return GetDataMemberSerialize(t, true);
        }
        /// 
        /// 把列表T序列化,格式:
        /// 4个字节 第一个元素 4个字节 第二个元素
        /// 
        /// 
        /// 
        /// 
        /// 
        private static byte[] GetDataMemberSerialize(T t, bool encry)
            where T:IList
        {
            Type type = typeof (T);
            Type dataType = type;
            

            if (type.GetInterface("IList")!=null)
            {
                dataType = type.GetGenericArguments()[0];
                int count = (int)type.GetProperty("Count").GetValue(t, null);
                
                MemoryStream ms = new MemoryStream();
                for(int i = 0;i < count;i++)
                {
                    MemoryStream m1 = new MemoryStream();
                    object io = type.GetMethod("get_Item").Invoke(t, new object[] { i });
                    var props = dataType.GetProperties().ToList();
                    props.ForEach(p =>
                    {
                        if (p.IsDefined(typeof(DataMemberAttribute), false))
                        {
                            byte[] name = Encoding.ASCII.GetBytes(p.Name);

                            m1.WriteByte(p.Name.GetByteSizeByte());
                            m1.Write(name,0,name.Length);
                            bool readed = false;

                            byte[] valLen = null;
                            byte[] val = null;
                            if(p.PropertyType ==typeof( string))
                            {
                                readed = true;
                                string strV = p.GetValue(io, null).ToString();
                                if (strV != null)
                                {
                                    valLen = strV.GetIntSizeByte();
                                    val = Encoding.UTF8.GetBytes(strV);
                                }
                            }

                            #region Guid
                            if (p.PropertyType == typeof(Guid))
                            {
                                readed = true;
                                Guid strV = new Guid(p.GetValue(io, null).ToString());

                                val = strV.ToByteArray();
                                valLen = new byte[] { (byte)val.Length };
                            }
                            if (p.PropertyType == typeof(Guid?))
                            {
                                readed = true;
                                Guid? strV = (Guid?)p.GetValue(io, null);
                                if (strV.HasValue)
                                {
                                    val = strV.Value.ToByteArray();
                                    valLen = new byte[] {(byte) val.Length};
                                }
                            }
                            #endregion

                            #region int
                            if (p.PropertyType ==typeof( int))
                            {
                                readed = true;
                                int strV = (int)(p.GetValue(io, null));

                                val = BitConverter.GetBytes(strV);
                                valLen = new byte[] { (byte)val.Length };
                            }
                            if (p.PropertyType ==typeof( int?))
                            {
                                readed = true;
                                int? strV = (int?)p.GetValue(io, null);
                                if (strV.HasValue)
                                {
                                    val = BitConverter.GetBytes(strV.Value);
                                    valLen = new byte[] { (byte)val.Length };
                                }
                            }
                            #endregion

                            #region byte
                            if (p.PropertyType ==typeof( byte))
                            {
                                readed = true;
                                byte strV = (byte)(p.GetValue(io, null));

                                val = BitConverter.GetBytes(strV);
                                valLen = new byte[] { (byte)val.Length };
                            }
                            if (p.PropertyType ==typeof( byte?))
                            {
                                readed = true;
                                byte? strV = (byte?)p.GetValue(io, null);
                                if (strV.HasValue)
                                {
                                    val = BitConverter.GetBytes(strV.Value);
                                    valLen = new byte[] { (byte)val.Length };
                                }
                            }
                            #endregion

                            #region DateTime
                            if (p.PropertyType == typeof(DateTime))
                            {
                                readed = true;
                                DateTime strV = (DateTime)(p.GetValue(io, null));
                                val = BitConverter.GetBytes(strV.ToBinary());
                                valLen = new byte[] { (byte)val.Length };
                            }
                            if (p.PropertyType ==typeof( DateTime?))
                            {
                                readed = true;
                                DateTime? strV = (DateTime?)p.GetValue(io, null);
                                if (strV.HasValue)
                                {
                                    val = BitConverter.GetBytes(strV.Value.ToBinary());
                                    valLen = new byte[] { (byte)val.Length };
                                }
                            }
                            #endregion

                            #region byte[]
                            if (p.PropertyType == typeof(byte[]))
                            {
                                readed = true;
                                byte[] strV = (byte[])(p.GetValue(io, null));

                                val = strV;
                                valLen = new byte[] { (byte)val.Length };
                            }
                            
                            #endregion

                            if(!readed)
                            {
                                throw new Exception(p.PropertyType.ToString() + "未设置");
                            }
                            if(val!=null&& valLen!=null)
                            {
                                m1.Write(valLen,0,valLen.Length);
                                m1.Write(val, 0, val.Length);
                            }
                        }
                    });
                    var end1 = m1.ToArray();
                    byte[] size = BitConverter.GetBytes(end1.Length);
                    ms.Write(size, 0, size.Length);
                    ms.Write(end1, 0, end1.Length);
                    
                }
                return ms.ToArray();
            }
            else
            {
                var props = type.GetProperties().ToList();
                props.ForEach(p =>
                {
                    if (p.IsDefined(typeof(DataMemberAttribute), false))
                    {
                        p.GetValue(t, null);
                    }
                });
            }
            return null;
        }

        /// 
        /// 返回对象序列化为byte数组
        /// 
        /// 对象类型
        /// 对象
        /// 是否压缩(默认压缩)
        /// 
        public static byte[] GetByteSerialize(T t,bool compress)
        {
            var memory = new MemoryStream();
            var formatter = new BinaryFormatter();
            formatter.Serialize(memory, t);
            memory.Position = 0;
            var read = new byte[memory.Length];
            memory.Read(read, 0, read.Length);
            memory.Close();
            if (compress)
            {
                read = CompressHelper.CompressBytes(read);
            }
            return read;
        }

        /// 
        /// 返回对象的反序列化
        /// 
        /// 对象类型
        /// byte数组
        /// 
        public static T GetByteDeserialize(byte[] pBytes)
        {
            return GetByteDeserialize(pBytes, true);
        }

        /// 
        /// 返回对象的反序列化
        /// 
        /// 对象类型
        /// byte数组
        /// 是否先进行解压操作
        /// 
        public static T GetByteDeserialize(byte[] pBytes,bool decompress)
        {
            if (pBytes == null)
                return default(T);
            if(decompress)
            {
                pBytes = CompressHelper.DecompressBytes(pBytes);
            }
            var memory = new MemoryStream(pBytes) {Position = 0};
            var formatter = new BinaryFormatter();
            object newOjb = formatter.Deserialize(memory);
            memory.Close();
            return (T)newOjb;
        }

        /// 
        /// 返回对T的XML序列化结果
        /// 
        /// 
        /// 
        /// 
        public static string GetXmlSerialize(T t)
        {
            string re;
            var ser = new XmlSerializer(typeof(T));
            using (var ms = new MemoryStream())
            using (var sw = new StreamWriter(ms))
            using (var sr = new StreamReader(ms))
            {
                ser.Serialize(sw, t);
                ms.Position = 0;
                re = sr.ReadToEnd();
            }
            return re;
        }
        /// 
        /// 对XML反序列化为对象
        /// 
        /// 
        /// 
        /// 
        public static T GetXmlDeserialize(string xmlString) where T : class
        {
            return GetXmlDeserialize(xmlString, Encoding.UTF8);
        }
        /// 
        /// 对XML反序列化为对象
        /// 
        /// 
        /// 
        /// 
        /// 
        public static T GetXmlDeserialize(string xmlString, Encoding encoding) where T : class
        {
            using (var memoryStream = new MemoryStream(encoding.GetBytes(xmlString)))
            using (var streamReader = new StreamReader(memoryStream, encoding))
            using (var xmlTextReader = new XmlTextReader(streamReader))
            {
                var ser = new XmlSerializer(typeof(T));
                if (ser.CanDeserialize(xmlTextReader))
                {
                    return ser.Deserialize(xmlTextReader) as T;
                }
            }
            return null;
        }

        /// 
        /// 根据对象的属性,生成另外一个对象,要求两个对象属性名称一样,类型一样
        /// 
        /// 
        /// 
        /// 
        /// 
        public static TOut GetClone(TInput t)
                where TOut : class,new()
        {
            TOut re = new TOut();
            Type toutType = typeof (TOut);
            Type tinputType = typeof(TInput);
            var toutProList = toutType.GetProperties();
            var tinputProList = tinputType.GetProperties();

            foreach (var inPro in tinputProList)
            {
                foreach (var outPro in toutProList)
                {
                    if(inPro.Name == outPro.Name &&
                        inPro.PropertyType == outPro.PropertyType
                        )
                    {
                        outPro.SetValue(re,inPro.GetValue(t,null),null);
                    }
                }
            }
            return re;
        }
        /// 
        /// 把数据实体对象转成可以序列化的对象列表
        /// 
        /// 
        /// 
        /// 
        /// 
        public static List GetDataTableList(Func> getAll)
            where T : class,new()
        {
            List et = new List();
            var lists = getAll();
            lists.ForEach(w => et.Add(SerializerHelper.GetClone(w)));
            return et;
        }
    }

你可能感兴趣的:(windows,C#)