I'm currently trying to deserialize a YAML document into standard .NET objects, such as string
for scalar values and Dictionary<string, object>
for mappings, using YamlDotNet library.
I guess that Deserializer
class is the best option, but its output is object
and Dictionary<object>
. I tried implementing custom INodeTypeResolver
like this:
class MyNodeTypeResolver : INodeTypeResolver
{
bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
{
if (currentType == typeof(object))
{
if (nodeEvent is SequenceStart)
currentType = typeof(List<object>);
else if (nodeEvent is MappingStart)
currentType = typeof(Dictionary<string, object>);
else if (nodeEvent is Scalar)
currentType = typeof(string);
return true;
}
return false;
}
}
and using it like this:
Deserializer deserializer = new Deserializer();
deserializer.TypeResolvers.Add(new MyNodeTypeResolver());
var res = deserializer.Deserialize(input);
but that doesn't seem to have any effect. Is there any way to change the type of objects produced by Deserializer
?
You're on the right track with INodeTypeResolver
but you need to build and use a custom deserializer:
DeserializerBuilder deserializerBuilder = new DeserializerBuilder()
.WithNodeTypeResolver(new MyNodeTypeResolver());
IDeserializer deserializer = deserializerBuilder.Build();
var res = deserializer.Deserialize(input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With