c# - protobuf-net 序列化为字符串存入数据库然后反序列化

标签 c# protobuf-net

我想使用字符串序列化/反序列化一个对象。请注意,当我对文件进行序列化/反序列化时,一切正常。我想要做的是获取一个字符串,这样我就可以将它存储在数据库中,然后稍后将其拉出进行反序列化。

这是有效的代码:

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) 中,这就是我想要字符串的原因。

如有任何帮助,我们将不胜感激!

最佳答案

我对在这种情况下使用 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);

关于c# - protobuf-net 序列化为字符串存入数据库然后反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6905585/

相关文章:

c# - 开始使用 protobuf-net

protobuf-net - protobuf 版本和 DateTimeOffset

Protobuf-net 对象图引用完整性

C#:引用应用程序资源文件

javascript - jQuery post方法参数传递失败

c# - 创建一个带标题的 .txt 文件

.net - 使用 protobuf-net 序列化数组时如何处理空值?

c# - 具有字典属性的 protobuf-net 类

c# - 覆盖 WinForm ListView 控件上的 Drawitem 事件

C# 迭代泛型对象