/// <summary>
/// 对象的序列化助手
/// </summary>
public static class SerializerHelper
{
/// <summary>
/// 返回对象序列化为byte数组
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="t">对象</param>
/// <returns></returns>
public static byte[] GetByteSerialize<T>(T t)
{
return GetByteSerialize(t, true);
}
public static byte[] GetDataMemberSerialize<T>(T t)
where T:IList
{
return GetDataMemberSerialize(t, true);
}
/// <summary>
/// 把列表T序列化,格式:
/// 4个字节 第一个元素 4个字节 第二个元素
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="encry"></param>
/// <returns></returns>
private static byte[] GetDataMemberSerialize<T>(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;
}
/// <summary>
/// 返回对象序列化为byte数组
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="t">对象</param>
/// <param name="compress">是否压缩(默认压缩)</param>
/// <returns></returns>
public static byte[] GetByteSerialize<T>(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;
}
/// <summary>
/// 返回对象的反序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="pBytes">byte数组</param>
/// <returns></returns>
public static T GetByteDeserialize<T>(byte[] pBytes)
{
return GetByteDeserialize<T>(pBytes, true);
}
/// <summary>
/// 返回对象的反序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="pBytes">byte数组</param>
/// <param name="decompress">是否先进行解压操作</param>
/// <returns></returns>
public static T GetByteDeserialize<T>(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;
}
/// <summary>
/// 返回对T的XML序列化结果
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string GetXmlSerialize<T>(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;
}
/// <summary>
/// 对XML反序列化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlString"></param>
/// <returns></returns>
public static T GetXmlDeserialize<T>(string xmlString) where T : class
{
return GetXmlDeserialize<T>(xmlString, Encoding.UTF8);
}
/// <summary>
/// 对XML反序列化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlString"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static T GetXmlDeserialize<T>(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;
}
/// <summary>
/// 根据对象的属性,生成另外一个对象,要求两个对象属性名称一样,类型一样
/// </summary>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TOut"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static TOut GetClone<TInput, TOut>(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;
}
/// <summary>
/// 把数据实体对象转成可以序列化的对象列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TOr"></typeparam>
/// <param name="getAll"></param>
/// <returns></returns>
public static List<T> GetDataTableList<T, TOr>(Func<List<TOr>> getAll)
where T : class,new()
{
List<T> et = new List<T>();
var lists = getAll();
lists.ForEach(w => et.Add(SerializerHelper.GetClone<TOr, T>(w)));
return et;
}
}
C#byte[]序列化及xml序列化,支持序列化后再压缩.
最新推荐文章于 2024-08-15 15:55:16 发布