Custom Element Serialization [Writable] (Advanced)
  • 04 Oct 2022
  • 1 Minute to read
  • Dark
    Light

Custom Element Serialization [Writable] (Advanced)

  • Dark
    Light

Article summary

Overview

In addition to marking up the object with attributes, there are a few interfaces that allow for customization of the storage and hooking events around the storage.

Specifying Custom Serialization

Using this interface, logic can be run on what to store, do conversions, and construction of unstable objects.

 public interface IWritable
{
     void Read(ReadStream stream);
     void Save(WriteStream stream);
}

Specifying Behavior Before Read

Using this interface, the object can be aware of being read in and can behave differently. An example use case would be for not taking some action when being read (deserialized) but performing action after.

 public interface IBeforeRead
{
   void BeforeRead();
}

Specifying Behavior Before Write

Using this interface, objects can be aware of being written. This is often used to rearrange data before the write happens.

 public interface IBeforeWrite
{
   void BeforeWrite();
}

Specifying Behavior After Reading

If some action needs to take place after an object (full object graph) has been read, this interface allows this to be changed.

 public interface IReadComplete
{
   void ReadComplete();
}

Changing Fault Behavior

If different behavior is desired when there is a problem, this interface allows adjustment.

 public interface ISerializationFaultPolicyBehavior
{
   SerializationFaultPolicy GetDeserializationFaultBehavior();
}

public enum SerializationFaultPolicy
{
   ThrowException,
   Tolerant
}

Code Example:

 public class Person : IWritable, IBeforeRead, IBeforeWrite, IReadComplete, ISerializationFaultPolicyBehavior
{
    private string name;

    public void Read(ReadStream stream)
    {
        name = stream.GetValue<string>("personname");
    }

    public void Save(WriteStream stream)
    {
        stream.Add("personname", name);
    }

    public void BeforeRead()
    {
    }

    public void BeforeWrite()
    {
        if (name == null)
            name = "unknown";
    }

    public void ReadComplete()
    {
        if (name.Contains(" "))
            name = name.Replace(" ", "");
    }

    public SerializationFaultPolicy GetDeserializationFaultBehavior()
    {
        return SerializationFaultPolicy.Tolerant;
    }
}</string>

Was this article helpful?