Kuczi
Kuczi

Reputation: 387

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?

Upvotes: 1

Views: 689

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

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.

Upvotes: 1

BWA
BWA

Reputation: 5764

If you use JSON.NET for serialization you can use Conditional Property Serialization

To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be serialized, if it returns false then the property will be skipped.

Example

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

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

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

    public bool SerializeVar2 {get; set; }

    public bool ShouldSerializeVar2
    {
        return SerializeVar2;
    }
}

Upvotes: 0

Related Questions