Search code examples
protobuf-net

An integer set to 0 is serialized(using protobuf-net) as null. Any workarounds to fix this problem?


Integer value set to 0 is serialized as null. it seems 0 is taken as default and ignored during serialization. Is there way to resolve this?


Solution

  • By default, protobuf-net follows proto3 conventions of zero===default===not-serialized, but you can override this behaviour by using IsRequired on the ProtoMemberAttribute:

    [ProtoMember(42, IsRequired = true)]
    public int Foo {get;set;}
    

    Alternatively, in more advanced scenarios, you can use "conditional serialization" (this same approach works with a wide range of serializers):

    [ProtoMember(42)]
    public int Foo {get;set;}
    
    public bool ShouldSerializeFoo() { /* your own rules here */ }