如何在YamlDotNet中反序列化YamlNode?

时间:2016-11-19 18:46:01

标签: c# serialization yaml yamldotnet

我有一个应用程序,我读取任意Yaml文件,其结构我事先不知道。我发现YamlStream和其他YamlNode实现很有用,因为它们允许我遍历整个Yaml文件。但是,在某些时候我有YamlNode,通常是YamlScalarNode,我想使用YamlDotNet将该节点反序列化为对象的能力。我怎么能这样做?

这是我尝试过的。这很丑陋,它只适用于具有显式标记的节点(例如!!bool "true"变为true,但1变为"1"):

private T DeserializeNode<T>(YamlNode node)
{
    if (node == null)
        return default(T);

    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    {
        new YamlStream(new YamlDocument[] { new YamlDocument(node) }).Save(writer);
        writer.Flush();
        stream.Position = 0;
        return new Deserializer().Deserialize<T>(reader);
    }
}

我必须有一个更好的方法,我还没有找到。

1 个答案:

答案 0 :(得分:3)

目前无法从YamlNode反序列化,您的方法是可能的解决方法之一。如果您想避免将节点写入缓冲区,可以实现从IParser读取的YamlNode接口,如this example

我在上面的示例中执行此操作的方法是创建一个将YamlNode转换为IRnumerable<ParsingEvent>的适配器:

public static class YamlNodeToEventStreamConverter
{
    public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlStream stream)
    {
        yield return new StreamStart();
        foreach (var document in stream.Documents)
        {
            foreach (var evt in ConvertToEventStream(document))
            {
                yield return evt;
            }
        }
        yield return new StreamEnd();
    }

    public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlDocument document)
    {
        yield return new DocumentStart();
        foreach (var evt in ConvertToEventStream(document.RootNode))
        {
            yield return evt;
        }
        yield return new DocumentEnd(false);
    }

    public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlNode node)
    {
        var scalar = node as YamlScalarNode;
        if (scalar != null)
        {
            return ConvertToEventStream(scalar);
        }

        var sequence = node as YamlSequenceNode;
        if (sequence != null)
        {
            return ConvertToEventStream(sequence);
        }

        var mapping = node as YamlMappingNode;
        if (mapping != null)
        {
            return ConvertToEventStream(mapping);
        }

        throw new NotSupportedException(string.Format("Unsupported node type: {0}", node.GetType().Name));
    }

    private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlScalarNode scalar)
    {
        yield return new Scalar(scalar.Anchor, scalar.Tag, scalar.Value, scalar.Style, false, false);
    }

    private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlSequenceNode sequence)
    {
        yield return new SequenceStart(sequence.Anchor, sequence.Tag, false, sequence.Style);
        foreach (var node in sequence.Children)
        {
            foreach (var evt in ConvertToEventStream(node))
            {
                yield return evt;
            }
        }
        yield return new SequenceEnd();
    }

    private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlMappingNode mapping)
    {
        yield return new MappingStart(mapping.Anchor, mapping.Tag, false, mapping.Style);
        foreach (var pair in mapping.Children)
        {
            foreach (var evt in ConvertToEventStream(pair.Key))
            {
                yield return evt;
            }
            foreach (var evt in ConvertToEventStream(pair.Value))
            {
                yield return evt;
            }
        }
        yield return new MappingEnd();
    }
}

一旦你有了这个,为IParser创建一个适配器是微不足道的,因为这两个接口基本上是等价的:

public class EventStreamParserAdapter : IParser
{
    private readonly IEnumerator<ParsingEvent> enumerator;

    public EventStreamParserAdapter(IEnumerable<ParsingEvent> events)
    {
        enumerator = events.GetEnumerator();
    }

    public ParsingEvent Current
    {
        get
        {
            return enumerator.Current;
        }
    }

    public bool MoveNext()
    {
        return enumerator.MoveNext();
    }
}

然后,您可以使用适配器从任何YamlStreamYamlDocumentYamlNode反序列化:

var stream = new YamlStream();
stream.Load(new StringReader(input));

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(new CamelCaseNamingConvention())
    .Build();

var prefs = deserializer.Deserialize<YOUR_TYPE>(
    new EventStreamParserAdapter(
        YamlNodeToEventStreamConverter.ConvertToEventStream(stream)
    )
);