7

我目前正在尝试使用 YamlDotNet 库将 YAML 文档反序列化为标准 .NET 对象,例如string标量值和映射。Dictionary<string, object>

我猜这个Deserializer类是最好的选择,但它的输出是objectand Dictionary<object>。我尝试INodeTypeResolver像这样实现自定义:

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;
    }
}

并像这样使用它:

Deserializer deserializer = new Deserializer();
deserializer.TypeResolvers.Add(new MyNodeTypeResolver());
var res = deserializer.Deserialize(input);

但这似乎没有任何效果。有什么办法可以改变产生的对象的类型Deserializer吗?

4

2 回答 2

1

您走在正确的轨道上,INodeTypeResolver但您需要构建和使用自定义反序列化器:

DeserializerBuilder deserializerBuilder = new DeserializerBuilder()
    .WithNodeTypeResolver(new MyNodeTypeResolver());
IDeserializer deserializer = deserializerBuilder.Build();
var res = deserializer.Deserialize(input);
于 2019-07-07T21:38:17.437 回答
0

AFAIK,反序列化采用类型参数,这真的很好

%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."

...

可以反序列化

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

前提是 MyMessage 具有 format 和 desc 属性,并且它不在命名空间中。如果是,您可以预先向反序列化器注册它,或者为它创建一个新标签。%TAG 别名似乎吃掉了标签的第一个字符,所以我放了一个下划线。也许是一个错误。另一种方法是注册它,

deserializer.RegisterTagMapping(
    "tag:yaml.org,2002:message", typeof(MyMessage));
于 2015-08-26T05:18:36.147 回答