Protobuf-net - 仅序列化一些属性
是否可以只序列化类的少数属性? 例如:
public class Client
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
public int Age { get; set; }
[ProtoMember(3)]
public string Guid { get; set; }
}
因此,我得到的“Id”值不正确。其他属性都是正确的。 如果我用“[ProtoMember]”填充所有属性,则“id”的值是正确的。 为什么?
实际上,该错误是由其他原因引起的,您也许可以帮助我。
我将 String 转换为 Stream 来执行任务。及时反转此转换,我的 Id 值出现错误
var cli = new Client
{ Id = 222, Guid = "52369-fe5r6-74e2g-j1i4e", Age = 29, Name = "José"};
//Serialize
var ms = new MemoryStream();
Serializer.Serialize(ms, cli);
ms.Position = 0;
var reader = new StreamReader(ms);
var strStream = reader.ReadToEnd();
//Deserialize
var ms2 = new MemoryStream(Encoding.UTF8.GetBytes(strStream));
var obj = Serializer.Deserialize<Client>(ms2);
,因此,任何高于 127 的值都会转换为不同的 Int。例如:3104751
我的转换错误?
Obs:抱歉英语不好
It is possible to serialize only a few properties of the class?
ex:
public class Client
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
public int Age { get; set; }
[ProtoMember(3)]
public string Guid { get; set; }
}
Thus, I get the value of "Id" incorrect. The other properties are correct.
If I fill it with "[ProtoMember]" all the properties, the value of "id" is correct.
Why?
Actually the error is caused by other reasons you may be able to help me.
I convert String to Stream to perform tasks. In time to reverse this conversion I have error in the value of Id
var cli = new Client
{ Id = 222, Guid = "52369-fe5r6-74e2g-j1i4e", Age = 29, Name = "José"};
//Serialize
var ms = new MemoryStream();
Serializer.Serialize(ms, cli);
ms.Position = 0;
var reader = new StreamReader(ms);
var strStream = reader.ReadToEnd();
//Deserialize
var ms2 = new MemoryStream(Encoding.UTF8.GetBytes(strStream));
var obj = Serializer.Deserialize<Client>(ms2);
Thus, any value above 127, is converted to a different Int. Ex: 3104751
My conversion is wrong?
Obs: I'm sorry the poor English
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是。只需确保包含类的 [ProtoContract] 属性,并在序列化和反序列化时使用完全相同的约定。
It is. Just make sure to include the [ProtoContract] attribute for the class and use the exact same contract when serializing and deserializing.
通过您的编辑,错误是显而易见的;您正在使用
Encoding
将任意数据处理为字符串。别担心,我经常看到(因此这篇文章)。文本编码的目的是:
这里重要的是
byte[]
具有由编码定义的特定重要值。你想要的是base-64:你可以通过:
然后:
With your edit, the error is obvious; you are using
Encoding
to process arbitrary data into a string. Don't worry, I see this a lot (hence this post).The intention of a text encoding is:
the important thing here is that the
byte[]
has a specific important defined by the encoding. What you want is base-64:which you do via:
and then:
问题是因为编码。您为什么要读取流然后创建另一个流?像这样的东西应该有效:
The problem is because of the encoding. Why are you reading the stream and then creating another one? Something like this should work: