我想使用字符串序列化/反序列化一个对象。需要注意的是,当我序列化/反序列化到一个文件时,一切都很正常。我要做的是获取一个字符串,这样我就可以将其存储在数据库中,然后将其提取出来进行反序列化。
下面是可以工作的代码:
MemoryStream msTest = new MemoryStream();
Serializer.Serialize(msTest, registrationBlocks);
msTest.Position = 0;
List<RVRegistrationBlock> CopiedBlocks = new List<RVRegistrationBlock>();
CopiedBlocks = Serializer.Deserialize<List<RVRegistrationBlock>>(msTest);
"CopiedBlocks“对象与"registrationBlocks”中的列表相同,一切都是序列化/反序列化的。我把所有的东西都放在这里了。
以下是当我试图获得一个字符串时不能工作的代码:
MemoryStream msTestString = new MemoryStream();
Serializer.Serialize(msTestString, registrationBlocks);
msTestString.Position = 0;
StreamReader srRegBlock = new StreamReader(msTestString);
byte[] bytedata64 = System.Text.Encoding.Default.GetBytes(srRegBlock.ReadToEnd());
string stringBase64 = Convert.ToBase64String(bytedata64);
byte[] byteAfter64 = Convert.FromBase64String(stringBase64);
MemoryStream afterStream = new MemoryStream(byteAfter64);
List<RVRegistrationBlock> CopiedBlocksString = new List<RVRegistrationBlock>();
CopiedBlocksString = Serializer.Deserialize<List<RVRegistrationBlock>>(afterStream);
在反序列化的最后一行,我得到了一个异常:抛出了'ProtoBuf.ProtoException‘类型的异常。我无法钻取它,内部异常为空。我不明白它为什么要这么做。
我已经明确地缩小了范围,当我涉及到一个字符串时,它就会变得混乱。我将字符串存储在数据库的nvarchar(max)中,这就是我需要该字符串的原因。
任何帮助都将不胜感激!
发布于 2011-08-02 07:58:00
在这种情况下,我对StreamReader
的使用有点迷惑,在我看来,您可以省略这一点,并像下面这样做,以确保不会发生单向编码。
MemoryStream msTestString = new MemoryStream();
Serializer.Serialize(msTestString, registrationBlocks);
string stringBase64 = Convert.ToBase64String(msTestString.ToArray());
byte[] byteAfter64 = Convert.FromBase64String(stringBase64);
MemoryStream afterStream = new MemoryStream(byteAfter64);
List<RVRegistrationBlock> CopiedBlocksString = new List<RVRegistrationBlock>();
CopiedBlocksString = Serializer.Deserialize<List<RVRegistrationBlock>>(afterStream);
发布于 2017-04-18 15:29:06
根据答案和评论,我使用以下内容:
internal static string SerializeToString_PB<T>(this T obj)
{
using (MemoryStream ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(ms, obj);
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
}
internal static T DeserializeFromString_PB<T>(this string txt)
{
byte[] arr = Convert.FromBase64String(txt);
using (MemoryStream ms = new MemoryStream(arr))
return ProtoBuf.Serializer.Deserialize<T>(ms);
}
发布于 2021-05-19 09:50:57
public static string ToProtobufString(this object model) {
using var memString = new MemoryStream();
Serializer.Serialize(memString, model);
return Convert.ToBase64String(memString.GetBuffer(), 0, (int)memString.Length);
}
public static T FromProtobufString<T>(this string protobuf) where T : class {
var byteAfter64 = Convert.FromBase64String(protobuf);
using var mem = new MemoryStream(byteAfter64);
return mem.FromProtobuf<T>();
}
https://stackoverflow.com/questions/6905585
复制相似问题