Customizing the serialization for specific models

Catel has a default behavior for what gets serialized. It can be tweaked by including / excluding fields and properties by using the IncludeInSerialization and ExcludeFromSerialization attributes. But sometimes one needs more specific customization of the serialization for a specific type. This customization is possible via the ISerializerModifier.

Creating the modifier

To customize the serialization of a specific model type, one needs to implement the ISerializerModifier interface. The example belows shows how to encrypt the Password property on the Person model class.

public class PersonSerializerModifier : SerializerModifierBase<Person>
{
    public override void SerializeMember(ISerializationContext context, MemberValue memberValue)
    {
        if (string.Equals(memberValue.Name, "Password"))
        {
            memberValue.Value = EncryptionHelper.Encrypt(memberValue.Value);
        }
    }
 
    public override void DeserializeMember(ISerializationContext context, MemberValue memberValue)
    {
        if (string.Equals(memberValue.Name, "Password"))
        {
            memberValue.Value = EncryptionHelper.Decrypt(memberValue.Value);
        }
    }
}

Registering the modifier

To register a modifier for a specific class, define the SerializerModifier attribute:

[SerializerModifier(typeof(PersonSerializerModifier))]
public class Person : ModelBase
{
    // .. class contents
}

Contributions

We would like to thank the following contributors:

Want to contribute to the documentation? We have a guide for that!


Questions

Have a question about Catel? Use StackOverflow with the Catel tag!


Discussion