AmbitiousD
AmbitiousD

Reputation: 35

Protobuf-net not serializing List

I am currently experimenting with protobuf-net (v3.0.29) and trying to serialize/deserialize some simple classes. From the minimal working example, I do not understand why protobuf-net serializes/deserializes the simple List<int> Value to a list with no elements.

    public enum BigEnum { One, Two }

    [ProtoContract]
    public class Container
    {
        [ProtoMember(1)]
        public BigEnum Parameter { get; private set; }
        [ProtoMember(2)]
        public List<int> Value { get; set; }
        public Container()
        {
            Parameter = BigEnum.One;
            Value = new List<int>();
        }
    }
    static class Program
    {
        static void Main(string[] args)
        {
            Container data = new Container();
            data.Value.Add(-1);
            data.Value.Add(1);

            MemoryStream memStream = new MemoryStream();
            Serializer.Serialize<Container>(memStream, data);
            var result = Serializer.Deserialize<Container>(memStream);
        }
    }

This protobuf-file was generated by Serializer.GetProto() and looks fine to me. How can we process List<int> Value correctly and can protobuf-net handle more complex structures like List<KeyValuePair<String, String>> or Dictionary<int,double> within a class? There are some very old posts for protobuf-net with dictionaries around but I don't know what's the current state.

syntax = "proto3";
package NetCoreProtobuf;

enum BigEnum {
   One = 0;
   Two = 1;
}
message Container {
   BigEnum Parameter = 1;
   repeated int32 Value = 2 [packed = false];
}

Upvotes: 1

Views: 614

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

Very simple: you didn't rewind the stream, so it read from the current position - at the end of the stream, with zero bytes to read. It happens to be the case that zero bytes is perfectly valid in protobuf, so it can't really raise an exception here, as you might be entirely correct in deserializing zero bytes.

Serializer.Serialize<Container>(memStream, data);
memStream.Position = 0;
var result = Serializer.Deserialize<Container>(memStream);

Or simpler: use the DeepClone method:

var clone = Serializer.DeepClone(data);

Upvotes: 1

Related Questions