Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to override the serializer properly #802

Closed
emanuel-v-r opened this issue Apr 27, 2023 · 3 comments
Closed

How to override the serializer properly #802

emanuel-v-r opened this issue Apr 27, 2023 · 3 comments
Labels

Comments

@emanuel-v-r
Copy link

emanuel-v-r commented Apr 27, 2023

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.

@EdwardCooke
Copy link
Collaborator

I’m linking this issue here since it looks like a potential solution. I’ll try and build a sample today or shortly

#510

@EdwardCooke
Copy link
Collaborator

Did that other issue solve your problem? Can I close this issue?

@EdwardCooke
Copy link
Collaborator

Since there hasn't been a response and the linked issue looks like it should solve the problem, I'm going to close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants