DataContract serialization with protobuf-net r275

你离开我真会死。 提交于 2019-12-12 09:27:46

问题


I just updated to r275 version and it doesn't seem to manage correctly DataContract classes any more By serializing this very simple class:

[DataContract]
public class ProtoData
{
    [DataMember(Order = 1)]
    private long _id;
    [DataMember(Order = 2)]
    private string _firstName;
    [DataMember(Order = 3)]
    private string _lastName;

    public long Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public ProtoData(long id, string firstName, string lastName)
    {
        _id = id;
        _firstName = firstName;
        _lastName = lastName;
    }

    public ProtoData()
    {
    }

I get Only data-contract classes (and lists/arrays of such) can be processed (error processing ProtoData)


回答1:


Really? that is.... odd; I would have expected the unit tests to spt such a breaking change. Are you sure you are using the right version? There is a 2.0 version (which doesn't include [DataContract] support, since this is in WCF, a 3.0 extension) and a separate 3.0 version. You want the 3.0 version (NET30.zip).

Tested successfully with r275/NET30:

static void Main() {
    ProtoData pd = new ProtoData {
        FirstName = "Marc",
        LastName = "Gravell",
        Id = 23354
    }, clone;
    using (MemoryStream ms = new MemoryStream()) {
        Serializer.Serialize(ms, pd);
        Console.WriteLine(ms.Length);
        ms.Position = 0;
        clone = Serializer.Deserialize<ProtoData>(ms);            
    }
    Console.WriteLine(clone.FirstName);
    Console.WriteLine(clone.LastName);
    Console.WriteLine(clone.Id);
}

With output:

19
Marc
Gravell
23354



回答2:


Try the following:

  • Remove all private members
  • Use public properties

    public string LastName;

  • Mark all public properties with [DataMember]



来源:https://stackoverflow.com/questions/1775082/datacontract-serialization-with-protobuf-net-r275

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!