- 11 Aug 2021
- 1 Minute to read
- Print
- DarkLight
Custom Element Serialization [Writable] (Advanced)
- Updated on 11 Aug 2021
- 1 Minute to read
- Print
- DarkLight
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.
IWritable Interface - Specifying Custom Serialization
Using this interface, logic can be run on what to store, do a conversion, and construction of unstable objects.
public interface IWritable
{
void Read(ReadStream stream);
void Save(WriteStream stream);
}
IBeforeRead Interface - Specifying Behavior Before Read
Using this interface, the object can know it is being read in and can behave differently. For example, when a user does not want to take some action when being read (deserialized) but wants to take action after.
public interface IBeforeRead
{
void BeforeRead();
}
IBeforeWrite Interface - Specifying Behavior Before Write
Using this interface allows objects to know they are about to be written. This is often used to rearrange data before the write happens.
public interface IBeforeWrite
{
void BeforeWrite();
}
IReadComplete Interface - 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();
}
ISerializationFaultPolicyBehavior Interface - 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;
}
}