Deserialize YAML to User Types

I am currently trying to deserialize a YAML document into standard .NET objects, such as stringfor scalar values ​​and Dictionary<string, object>for mappings, using the YamlDotNet library.

I assume the class Deserializeris the best option, but its conclusion is objectand Dictionary<object>. I tried to implement my own INodeTypeResolveras follows:

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 this does not seem to have any effect. Is there a way to change the type of objects produced Deserializer?

+5
source share
2 answers

AFAIK, Deserialize accepts a type parameter that is really good

%YAML 1.1
%TAG !namespace! _MyNamespace.NestedClass.Whatever.
---

entry_0: !namespace!MyMessage
  format: Alert
  desc: "Entry One! Uses the exact string representation of the desired type. (A bit fragile, IMHO)"

entry_1: !!message
  format: Default
  desc: "Entry Two! Uses a type registered beforehand."

entry_2:
  format: Default
  desc: "Entry Three! Just winging it, sometimes YamlDotNet is exceedingly clever."

...

can be deserialized

var dict = new Deserializer().Deserialize<Dictionary<string,MyMessage>>(
    new StringReader(that_doc_up_there));

, MyMessage format desc , . , Deserializer . , % TAG , . , . - ,

deserializer.RegisterTagMapping(
    "tag:yaml.org,2002:message", typeof(MyMessage));
0

INodeTypeResolver :

DeserializerBuilder deserializerBuilder = new DeserializerBuilder()
    .WithNodeTypeResolver(new MyNodeTypeResolver());
IDeserializer deserializer = deserializerBuilder.Build();
var res = deserializer.Deserialize(input);
0

Source: https://habr.com/ru/post/1537267/


All Articles