我想将对象序列化为字符串,然后再反序列化。
我们使用protobuf-net将对象转换为流并成功地将其反转回来。
但是,将流转换为字符串再反转回去的操作却不成功。经过StreamToString
和StringToStream
两个方法后,新的Stream
对象无法被protobuf-net反序列化;它会引发一个Arithmetic Operation resulted in an Overflow
异常。如果我们对原始流进行反序列化,那么就可以正常工作。
我们使用的方法:
public static string StreamToString(Stream stream)
{
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
public static Stream StringToStream(string src)
{
byte[] byteArray = Encoding.UTF8.GetBytes(src);
return new MemoryStream(byteArray);
}
我们使用这两个来示范代码:
MemoryStream stream = new MemoryStream();
Serializer.Serialize<SuperExample>(stream, test);
stream.Position = 0;
string strout = StreamToString(stream);
MemoryStream result = (MemoryStream)StringToStream(strout);
var other = Serializer.Deserialize<SuperExample>(result);