MaYaN
MaYaN

Reputation: 7006

Why can I not deserialize my object correctly using ProtoBuf-Net?

I have just started working with ProtoBuf-Net and have the following objects:

[DataContract]
public class Statistics
{
    [DataMember(Order = 1)]
    public DateTime DateTimeAsUtc { get; set; }

    [DataMember(Order = 2)]
    public IEnumerable<StatisticsRow> TopHashTags { get; set; }

    [DataMember(Order = 3)]
    public IEnumerable<StatisticsRow> TopWords { get; set; }    
}

[DataContract]
public class StatisticsRow
{
    [DataMember(Order = 1)]
    public string Key { get; set; }

    [DataMember(Order = 2)]
    public int Count { get; set; }
}


// Serialize then DeSerialize
using (var stream = new MemoryStream())
{
    Serializer.Serialize(stream, stats);

    stream.Seek(0, SeekOrigin.Begin);
    var deserialized = Serializer.Deserialize<Statistics>(stream);
}

When I serialize and try deserializing the object I get the default value for DateTimeAsUtc and null for all the other properties. Any ideas on what I am doing wrong?

Note that I have tried replacing DataContract and DataMember with ProtoContract and ProtoMember to no avail.

The issue only happens when in Release mode.

[Update]
The issue turned out to be due to existence of [MyConsoleApp].vshost.exe which apparently is a special version of the executable to aid debugging which I thought would be re-generated after a Rebuild (clearly not) so the solution was to manually delete it and now everything works just fine :-)

I am going to accept Marc's answer anyway as he was kind enough to follow it up and was very quick to reply.

Upvotes: 1

Views: 899

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063884

Using your example as a base, this works fine for me:

using (var stream = new MemoryStream()) {
    var stats = new Statistics {
        DateTimeAsUtc = DateTime.UtcNow,
        TopWords = new List<StatisticsRow> {
            new StatisticsRow { Count = 1, Key = "abc" }
        },
        TopHashTags = new List<StatisticsRow> {
            new StatisticsRow { Count = 2, Key = "def" }
        }
    };
    Serializer.Serialize(stream, stats);

    stream.Seek(0, SeekOrigin.Begin);
    var deserialized = Serializer.Deserialize<Statistics>(stream);
    Console.WriteLine(deserialized.DateTimeAsUtc);
    foreach(var row in deserialized.TopWords)
        Console.WriteLine("{0}: {1}", row.Key, row.Count);
    foreach (var row in deserialized.TopHashTags)
        Console.WriteLine("{0}: {1}", row.Key, row.Count);
}

So... it probably needs a complete (failing) example to be answerable. The first thing to check, however, is stream.Length; if that is 0, there was no data serialized. As an aside and for your convenience: that implementation is akin to:

var deserialized = Serializer.DeepClone(stats);

Upvotes: 3

Related Questions