Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing YAML into Custom Types

Tags:

c#

yamldotnet

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?

like image 676
mavsic Avatar asked Apr 20 '14 11:04

mavsic


1 Answers

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);
like image 105
Nick Avatar answered Oct 14 '22 12:10

Nick