protobuffer .net 序列化

/// <summary>
/// protobuffer 序列化工具类
/// </summary>
/// <typeparam name="T"></typeparam>
public class ProtoBufferUtil<T> where T : class
{
/// <summary>
/// 对象序列化
/// </summary>
/// <param name="fromObj"></param>
/// <returns></returns>
public static byte[] SerializeToBinary(T fromObj)
{
byte[] result =new byte[0];
using (MemoryStream stream = new System.IO.MemoryStream())
{
ProtoBuf.Serializer.Serialize<T>(stream, fromObj);
result= stream.ToArray();
stream.Close();
}
return result;
}

/// <summary>
/// 对象序列化
/// </summary>
/// <param name="fromObj"></param>
/// <returns></returns>
public static string SerializeToString(T fromObj)
{
string result =string.Empty;
using (MemoryStream stream = new System.IO.MemoryStream())
{
ProtoBuf.Serializer.Serialize<T>(stream, fromObj);
result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
stream.Close();
}
return result;
}

/// <summary>
/// 对象反序列化
/// </summary>
/// <param name="jsonStr"></param>
/// <param name="settings"></param>
/// <returns></returns>
public static T DeserializeFromString(string jsonStr)
{
T result = default(T);
if (!string.IsNullOrEmpty(jsonStr))
{
byte[] bt = System.Text.Encoding.UTF8.GetBytes(jsonStr);
if (bt != null && bt.Length > 0)
{
using (MemoryStream stream = new System.IO.MemoryStream(bt))
{
result = ProtoBuf.Serializer.Deserialize<T>(stream);
stream.Close();
}
}
}
return result;
}

/// <summary>
/// 对象反序列化
/// </summary>
/// <param name="jsonStr"></param>
/// <param name="settings"></param>
/// <returns></returns>
public static T DeserializeFromBinary(byte[] data)
{
T result = default(T);
if (data != null && data.Length>0)
{
using (MemoryStream stream = new System.IO.MemoryStream(data,0,data.Length,false))
{
result = ProtoBuf.Serializer.Deserialize<T>(stream);
stream.Close();
}
}
return result;
}

/// <summary>
/// 对象反序列化
/// </summary>
/// <param name="jsonStr"></param>
/// <param name="settings"></param>
/// <returns></returns>
public static T DeserializeFromStream(Stream stream)
{
T result = default(T);
if (stream != null)
{
result = ProtoBuf.Serializer.Deserialize<T>(stream);
stream.Close();
}
return result;
}

/// <summary>
/// 获取proto定义内容
/// </summary>
/// <returns></returns>
public static string GetProto()
{
return ProtoBuf.Serializer.GetProto<T>();
}
}

 

posted @ 2014-12-02 15:32  枯树之花  阅读(382)  评论(0编辑  收藏  举报