Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProtoBuf.NET not serializing when using DataContract attributes

Tags:

protobuf-net

I'm using the latest version of ProtoBuf on NuGet (2.0.0.480) and it does not serialize types marked with DataContract/DataMember attributes:

[DataContract]
public class Person
{
    [DataMember]
    public string Firstname { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "person.dat");

        var person = new Person { Firstname = "ben" };

        using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate)) {
            Serializer.Serialize(fs, person);
        }

        using (var fs = File.OpenRead(outputFile))
        {
            var result = Serializer.Deserialize<Person>(fs);
            Console.WriteLine(result.Firstname);
        }

        Console.ReadLine();
    }
}

However, if I decorate my class using the ProtoBuf specific attributes:

[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public string Firstname { get; set; }
}

It works as expected.

like image 908
Ben Foster Avatar asked Sep 10 '12 14:09

Ben Foster


3 Answers

It needs the Order property to get a unique and reliable key-number:

[DataContract]
public class Person
{
    [DataMember(Order=1)]
    public string Firstname { get; set; }
}
like image 104
Marc Gravell Avatar answered Nov 19 '22 14:11

Marc Gravell


I should have read the docs more closely, when using [DataMember] an Order must be specified.

e.g.

[DataMember(Order = 1)]

like image 2
Ben Foster Avatar answered Nov 19 '22 15:11

Ben Foster


In addition to Marc and Ben answers, note that you have to set the order values greater than 0.
we used to start the order from 0 when using the BCL serializers but protobuf-net is ignoring data members with order as 0.

like image 2
Tamir Avatar answered Nov 19 '22 14:11

Tamir