1

I am try to make conditional serialization base on rules that I give the moment I make the Serialization.

I know that I can use the ShouldSerialize+Name

[ProtoContract]
public class SomeType {
    [ProtoMember(1)]
    public string Name {get;set;}

    private bool ShouldSerializeName() {
       // return true to serialize Name, false otherwise
    }
}

But what I need is like this example on Newtonsoft.Json.JsonConvert where I give the settings for what i am going to serialize the moment of serialization.

var oResolFilter = new ShouldSerializeContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = oResolFilter };
var Results = JsonConvert.SerializeObject(this, settings);

and

class ShouldSerializeContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);    
        property.ShouldSerialize = true ; // ( or false)    
        return property;
    }
}

So the question is - how can I do something similar as the JsonConvert on ProtoBuf-Net

reference

I look on most of answers, and on the examples and the source code on protobuf-net but fail to locate a similar solution... here are few questions that I look.

.net serialization: how to selectively ignore data fields
Conditional serialization with protobuf-net
Protobuf-net serialization of object (generic) throws error No serializer defined for type: System.Object
How to ignore default values while serializing json with Newtonsoft.Json

json.net example: Newtonsoft JSON ShouldSerialize and inheritance

Aristos
  • 66,005
  • 16
  • 114
  • 150
  • How about a before-serialization callback with a serialization context that has the info you need to make decisions? – Marc Gravell Apr 25 '21 at 16:41
  • @MarcGravell and how can I do that ? – Aristos Apr 25 '21 at 18:09
  • I'm not at a PC, but: there should be a [ProtoBeforeSerialization] attribute, that you can put on a method of your choosing, and which can optionally take a `SerializationContext` that allows you to pass in external state (you should be able to provide that state via the API, or perhaps when creating the ProroWriter - again, I'm not at a PC) – Marc Gravell Apr 25 '21 at 20:10
  • @MarcGravell thank you, I am going to search for it – Aristos Apr 25 '21 at 20:50
  • 1
    k; if you can't find it, ping me and I'll whip up an example – Marc Gravell Apr 26 '21 at 06:17
  • @MarcGravell Do you have an example for above ? Thanks. – Anu Viswan Nov 07 '22 at 10:17

0 Answers0