The serialization logic can be extended by defining custom type converters either by implementing the IDynamoAttributeConverter
interface or deriving from the ADynamoAttributeConverter
base class.
The converter must implement the CanConvert()
, the ToAttributeValue()
, and one of the deserialization methods:
FromBool()
to convert fromAttributeValue.BOOL
FromBinary()
to convert fromAttributeValue.B
FromNumber()
to convert fromAttributeValue.NS
FromString()
to convert fromAttributeValue.S
FromList()
to convert fromAttributeValue.L
FromMap()
to convert fromAttributeValue.M
FromBinarySet()
to convert fromAttributeValue.BS
FromNumberSet()
to convert fromAttributeValue.NS
FromStringSet()
to convert fromAttributeValue.SS
Optionally, the converter can also implement GetDefaultValue()
to control the default value used to initialize a property that was not deserialized.
The following converter serializes TimeSpan
from and to an AttributeValue
instance.
class DynamoTimeSpanConverter : ADynamoAttributeConverter {
//--- Methods ---
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(TimeSpan);
public override AttributeValue ToAttributeValue(object value, Type targetType, DynamoSerializerOptions options)
=> new AttributeValue {
N = ((TimeSpan)value).TotalSeconds.ToString(CultureInfo.InvariantCulture)
};
public override object FromNumber(string value, Type targetType, DynamoSerializerOptions options) {
if(!double.TryParse(value, System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var parsedValue)) {
throw new DynamoSerializationException("invalid value for TimeSpan");
}
return TimeSpan.FromSeconds(parsedValue);
}
}
The custom converter must then be added to the serialization options to become available.
var document = DynamoSerializer.Serialize(item, new DynamoSerializerOptions {
Converters = {
new DynamoTimeSpanConverter()
}
});