问题描述
我想序列化/反序列化使用字符串对象。只是要注意,当我序列化/反序列化到一个文件,一切工作正常。我想要做的就是得到一个字符串,所以我可以将其存储在数据库中,然后将其拉出后反序列化。
I'd like to serialize/de-serialize an object using a string. Just to note, when I serialize/de-serialize to a file everything works fine. What I'm trying to do is get a string so I can store it in the database and then pull it out later to de-serialize.
下面是代码工作
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相同的列表伟大工程,一切系列化/反序列化。 。我让这里的一切溪流
The "CopiedBlocks" object is the same list that was in "registrationBlocks" Works great, everything serialized/de-serialized. I'm keeping everything in streams here.
下面是当我尝试涉足一个字符串,不工作的代码:
Here is the code that doesn't work when I try to get a string involved:
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'被抛出。我不能钻了进去,内部异常为空。我想不通为什么它这样做。
On the last line when it goes to deserialize, I get an exception: Exception of type 'ProtoBuf.ProtoException' was thrown. I can't drill into it, inner exception is null. I can't figure out why it's doing it.
我肯定把范围缩小到,当我得到一个字符串,它涉及的事实发生故障而导致。我存储一个nvarchar(max)存储在数据库中的字符串,这就是为什么我想要的字符串。
I've definitely narrowed it down to the fact that when I get a string involved it goes haywire. I'm storing the string in a database in an nvarchar(max) which is why I want the string.
任何帮助将是非常感激!
Any help would be super appreciated!
推荐答案
我有点在这种情况下所使用的的StreamReader
丢失,它会在我看来,你可以省略,并完成类似下面,以确保没有一个编码单向发生..
I am little bit lost by the use of the StreamReader
in this context, it would seem to me that you could omit that and do something like below to ensure there isn't a one-way encoding happening..
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);
这篇关于protobuf网序列化到字符串并存储在数据库然后序列化德的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!