[英]deserialize “long” string with protobuf for c# doesn't work properly for me
我顯然做了一些基本的錯誤,但我無法弄明白,也找不到文檔。
我正在嘗試使用Marc Gravell的.NET for proto-buf,並嘗試序列化和反序列化對象。 一旦一個對象包含一個“太長”的字符串(沒有試圖確定大小閾值,但它只有幾百個字節),字符串不會為我正確反序列化。
這是我的代碼:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using ProtoBuf;
namespace ConsoleApplication1
{
public class Program
{
[ProtoContract]
public class test
{
[ProtoMember(1)]
public int i;
[ProtoMember(2)]
public string s1;
[ProtoMember(3)]
public string s2;
[ProtoMember(4)]
public char[] arrchars;
[ProtoMember(5)]
public Dictionary<int, string> Dict = new Dictionary<int, string>();
}
static void Main(string[] args)
{
test var1 = new test();
var1.i = 10;
var1.s1 = "Hello";
var1.arrchars = new char[] {'A', 'B', 'C'};
var1.Dict.Add(10, "ten");
var1.Dict.Add(5, "five");
var1.s2 = new String('X', 520);
string s = PBSerializer.Serialize(typeof (test), var1);
test var2 = null;
PBSerializer.Deserialize(s, out var2);
}
public static class PBSerializer
{
public static string Serialize(Type objType, object obj)
{
MemoryStream stream = new MemoryStream();
ProtoBuf.Serializer.Serialize(stream, obj);
// ProtoBuf.Serializer.SerializeWithLengthPrefix(stream, obj, PrefixStyle.Fixed32, 1);
stream.Flush();
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string res = sr.ReadToEnd();
stream.Dispose();
sr.Dispose();
return res;
}
public static void Deserialize(string serializedObj, out test obj)
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(serializedObj));
obj = ProtoBuf.Serializer.Deserialize<test>(stream);
// obj = ProtoBuf.Serializer.DeserializeWithLengthPrefix<test>(stream, PrefixStyle.Fixed32, 1);
stream.Dispose();
}
}
}
}
var2.s2與var1.s2不同 - 它在字符串的開頭有一個額外的字符,並截斷字符串結尾的大部分。 但是,如果我將var1.s2的長度更改為一個較小的數字(比如52而不是520個字符),我的問題就會消失,但我需要能夠序列化長字符串。 我假設它與設置PrefixStyle(?)的錯誤有關,或者我可能沒有使用正確的編碼(?)。 但是,反復試驗並沒有幫助我解決問題。
我正在使用.NET 3.5並嘗試使用版本444和450,結果相同。
謝謝。
您正在序列化二進制數據 - 但隨后嘗試將其讀取為文本。 它不是 - 所以不要這樣做。
如果必須將任意二進制數據轉換為文本,請使用Convert.ToBase64String
和Convert.FromBase64String
。
public static class PBSerializer
{
public static string Serialize(Type objType, object obj)
{
using (MemoryStream stream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(stream, obj);
return Convert.ToBase64String(stream.ToArray());
}
}
// Ideally change this to use a return value instead of an out parameter...
public static void Deserialize(string serializedObj, out test obj)
{
byte[] data = Convert.FromBase64String(serializedObj);
using (MemoryStream stream = new MemoryStream(data))
{
obj = ProtoBuf.Serializer.Deserialize<test>(stream);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.