我想使用protobuf-net序列化字符串和反序列化回到对象。如果我序列化为.bin文件,它工作正常但是下面的代码在反序列化时抛出异常。有什么想法吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using ProtoBuf;
namespace Proto
{
class Program
{
public long MemUsed = 0;
NetDataContractSerializer ser = new NetDataContractSerializer();
static void Main(string[] args)
{
var person = new Person {
Id = 12345, Name = "Fred",
Address = new Address
{
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
Console.WriteLine("Serializing .....");
var result = Serialize<Person>(person);
Console.WriteLine(" Serialization Complete .....");
Console.WriteLine("Press key to Deserialize ....");
Console.ReadKey();
var person2 = new Person();
DeSerialize<Person>(ref person2,result);
Console.WriteLine(person2.Name);
Console.ReadLine();
}
public static string Serialize<T>(T myObj)
{
string retVal = "";
using (MemoryStream memStream = new MemoryStream())
{
Serializer.Serialize<T>(memStream, myObj);
memStream.Position = 0;
retVal = new StreamReader(memStream).ReadToEnd();
}
return (retVal);
}
public static void DeSerialize<T>(ref T myObj, string xmlString)
{
byte[] byteArray = Encoding.ASCII.GetBytes(xmlString);
MemoryStream stream = new MemoryStream(byteArray,0,byteArray.Length);
stream.Capacity = Convert.ToInt32(stream.Length);
myObj = Serializer.Deserialize<T>(stream);
stream.Close();
}
}
[ProtoContract]
class Person {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public Address Address {get;set;}
}
[ProtoContract]
class Address {
[ProtoMember(1)]
public string Line1 {get;set;}
[ProtoMember(2)]
public string Line2 {get;set;}
}
}
答案 0 :(得分:4)
您正在使用TextReader处理非文本二进制块。这不起作用;基本上你通过尝试UTF解码非UTF的东西来破坏二进制文件,然后重新编码你获得的(无意义的)字符串。
返回二进制文件(例如byte []),或者必须是字符串:通过Convert.ToBase64String等使用base-64。
另请参阅:http://marcgravell.blogspot.com/2010/03/binary-data-and-strings.html
答案 1 :(得分:0)
我在这里发布了一个与protobuf-net类似的问题,答案显示了如何进行base64转换。
protobuf-net Serialize To String and Store in Database Then De Serialize