Custom Element Serialization [Writable] (advanced)
  • Updated on 09 Dec 2013
  • 1 minute to read
  • Print
  • Dark
    Light

Custom Element Serialization [Writable] (advanced)

  • Print
  • Dark
    Light

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.

  1. Specifying Custom Serialization

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

 public interface IWritable
{
    void Read(ReadStream stream);
    void Save(WriteStream stream);
}
  1. Specifying Behavior Before Read

Object can know they are being read in and it can behave differently.  For example, if you do not want to take some action when being read (deserialized) that might be appropriate after.

 public interface IBeforeRead
{
   void BeforeRead();
}
  1. Specifying Behavior Before Write

Objects can know they are about to be written.  This is often used to rearrange data before the write happens.

 public interface IBeforeWrite
{
   void BeforeWrite();
}
  1. Specifying Behavior After Read

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();
}
  1. 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
}

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?