Search code examples
c#serializationdatacontractserializer

C# How to serialize an object in different ways


Let's say I have a class that I want to to be able to serialize that looks like this:

public class SomeClass
{
    [DataMember]
    public object Var1 {get; set; }

    [DataMember]
    public object Var2 {get; set; }

    [DataMember]
    public object Var3 {get; set; }
}

Sometimes I want it to be serialized with Var3 omited, so basically like this:

public class SomeClass
{
    [DataMember]
    public object Var1 {get; set; }

    [DataMember]
    public object Var2 {get; set; }

    public object Var3 {get; set; }
}

and in other cases I want it with Var2 omited.

Is there any way of decorating the class with attributes that will enable me to choose in what way i want this class serialized?


Solution

  • Add EmitDefaultValue parameter to attribute.

    public class SomeClass
    {
        [DataMember]
        public string Var1 { get; set; }
    
        [DataMember(EmitDefaultValue = false)]
        public object Var2 { get; set; }
    
        [DataMember(EmitDefaultValue = false)]
        public object Var3 { get; set; }
    }
    

    When you want omit Var2, set it to null.

    SomeClass sc = ...;
    sc.Var2 = null;
    

    In result it will be omitted.