Protobuf.net does not serialize zero

It looks like there is a problem with encoding for 0 as Int64. Other values ​​like Int64 ok.

[ProtoMember(3)] private readonly Int64 _intValue

      

deserialized as Int64.MinValue

Any idea?

I acknowledge the error. This class will not serialize correctly if _val == 0

[ProtoContract]

class VerySimple
{
    [ProtoMember(1)]
    private readonly Int64 _val = Int64.MinValue;

    public VerySimple(long val)
    {
        _val = val;
    }

    public long Val
    {
        get { return _val; }            
    }

    public VerySimple()
    {
    }
}

      

this test fails

[Test]

    public void TestProtobufEncodingSimple()
    {
        //OK
        {
            MemoryStream stream = new MemoryStream();
            Serializer.Serialize(stream, new VerySimple(1));
            stream.Seek(0, SeekOrigin.Begin);
            VerySimple reloaded = Serializer.Deserialize<VerySimple>(stream);
            Assert.AreEqual(reloaded.Val, 1L);
        }

        //KO
        {
            MemoryStream stream = new MemoryStream();
            Serializer.Serialize(stream, new VerySimple(0));
            stream.Seek(0, SeekOrigin.Begin);
            VerySimple reloaded = Serializer.Deserialize<VerySimple>(stream);
            Assert.AreEqual(reloaded.Val, 0L);
        }
    }

      

+2


source to share


1 answer


sorry for the delay - i had a few days offline; -p

The protocol buffers specification has an implicit default for most types. To maintain compatibility with processing, it respects this default unless otherwise noted. I'll try to make it clearer in the documentation.



There are several solutions:

  • Add an attribute [DefaultValue(int.MinValue)]

    to the field to set an explicit default value
  • Add IsRequired = true

    to attribute[ProtoMember]

  • If you are using Nullable<int>

    I suspect it will treat null as explicit
  • In the case of properties, it respects the pattern ShouldSerialize*

    , so if the property Val

    (with setter) has [ProtoMember]

    , it will lookbool ShouldSerializeVal()

+1


source







All Articles