protobuf-net 对象二进制序列化与反序列号(转)

概述:

Protobuf是google开源的一个项目,用户数据序列化反序列化,google声称google的数据通信都是用该序列化方法。它比xml格式要少的多,甚至比二进制数据格式也小的多。

Protobuf格式协议和xml一样具有平*立性,可以在不同平台间通信,通信所需资源很少,并可以扩展,可以旧的协议上添加新数据;

Protobuf是在java和c++运行的,Protobuf-net当然就是Protobuf在.net环境下的移植。

使用:

1、安装,通过NuGet安装Protobuf-net;

2、代码使用事例:

定义序列号帮助类

public class ProtoBufHelper
{
public static byte[] Serializeby(object obj)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, obj);
return stream.ToArray();
}
}
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string Serialize<T>(T t)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize<T>(ms, t);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="content"></param>
/// <returns></returns>
public static T DeSerialize<T>(string content)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t = Serializer.Deserialize<T>(ms);
return t;
}
}
}

定义序列号对象:

 [ProtoContract]
//[Serializable]
public class Person
{
[ProtoMember()]
public int Id { get; set; }
[ProtoMember()]
public string Name { get; set; }
[ProtoMember()]
public Address Address { get; set; }
}
[ProtoContract]
//[Serializable]
public class Address {
[ProtoMember()]
public string Line1 { get; set; }
[ProtoMember()]
public string Line2 { get; set; }
}

序列化方法调用:

static void Main(string[] args)
{
var p1 = new Person
{
Id = ,
Name = "八百里开外",
Address = new Address
{
Line1 = "Line1",
Line2 = "Line2"
}
};
var p2 = new Person
{
Id = ,
Name = "一枪",
Address = new Address
{
Line1 = "Flat Line1",
Line2 = "Flat Line2"
}
};
List<Person> pSource = new List<Person>() { p1, p2 };
var Curr = ProtoBufHelper.Serializeby(pSource); string content = ProtoBufHelper.Serialize<List<Person>>(pSource);
Console.Write(content);
//
File.WriteAllText("D://Hell.bin", content);
Console.WriteLine("*****解析二进制***");
List<Person> pResult = ProtoBufHelper.DeSerialize<List<Person>>(content);
foreach (Person p in pResult)
{
Console.WriteLine(p.Name);
}
Console.Read(); }
上一篇:HDU 2586 How far away ?【LCA模板题】


下一篇:java垃圾回收算法