How to override the serializer properly
emanuel-v-r opened this issue · comments
I would like to understand how to override the serializer properly.
I understand I can create a custom event emitter or type converter but I am not sure if it works well for me in this case.
Consider that I have this class, which is only a wrapper (I will add behavior to it later):
public class ValueWrapper<T>
{
public T Value { get; set; }
}
My goal is to serialize only the inner Value
, and do the same for deserialize.
For the deserializer I could do something like this:
public class YAMLValueDeserializer : INodeDeserializer
{
public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
{
if (expectedType.IsGenericType && expectedType.GetGenericTypeDefinition() == typeof(ValueWrapper<>))
{
var innerType = expectedType.GetGenericArguments().FirstOrDefault();
// this is the most important line, as it uses the built-in deserializers
var innerValue = nestedObjectDeserializer(parser, innerType);
value = (Activator.CreateInstance(typeof(ValueWrapper<>).MakeGenericType(innerType)));
value.GetType()
.GetProperty("Value")
.SetValue(value, innerValue);
return true;
}
value = null;
return false;
}
}
My goal is to do the same for the serializer, by serializing the inner Value
. The problem is that I want to use the built in serializer for the inner Value
which is of T
type, using something like "nestedObjectDeserializer".
With the EventEmitter seems that I would need to understand what type of event this T
corresponds to, but that would be duplicated work as the lib already does that for me.