【问题标题】:Trying to convert YAML file to hashtable using yamldotnet尝试使用 yamldotnet 将 YAML 文件转换为哈希表
【发布时间】:2016-07-12 22:16:09
【问题描述】:

现在我正在尝试利用 YamlDotNet 库中提供的反序列化器将 YAML 文件转换为哈希表。收到错误Excpected 'SequenceStart' got 'MappingStart'

var d = Deserializer();

var result = d.Deserialize<List<Hashtable>>(new StreamReader(*yaml path*));
foreach (var item in result)
{
    foreach (DictionaryEntry entry in item)
    {
        //print out using entry.Key and entry.Value and record
    }
}

YAML 文件结构如下所示

Title:

    Section1:
           Key1:    Value1
           Key2:    Value2
           Key3:    Value3

有时包含多个部分。

我也尝试过类似于Seeking guidance reading .yaml files with C# 的解决方案,但是发生了同样的错误。如何正确读取 YAML 文件,并使用 YamlDotNet 将其转换为哈希?

【问题讨论】:

    标签: c# yaml hashtable yamldotnet


    【解决方案1】:

    您正在尝试将您的 YAML 输入反序列化为列表:

    d.Deserialize<List<Hashtable>>
    //            ^^^^
    

    但是 YAML 文件中最上面的对象是一个映射(以 Title: 开头)。这就是您收到错误的原因。

    你的结构有四个层次。顶层将字符串 (Title) 映射到第二层。第二级将字符串 (Section1) 映射到第三级。第三级将字符串 (Key1) 映射到字符串 (Value1)。

    因此,您应该反序列化为:

    Dictionary<string, Dictionary<string, Dictionary<string, string>>>
    

    如果你最上面的对象总是只有一个键值对(以Title为键),你可以写一个类:

    public class MyClass {
        public Dictionary<string, Dictionary<string, string>> Title { get; set; }
    }
    

    然后对这个类使用反序列化:

    var result = d.Deserialize<MyClass>(new StreamReader(/* path */));
    foreach (var section in result.Title) {
        Console.WriteLine("Section: " + section.Key);
        foreach (var pair in section.Value) {
            Console.WriteLine("  " + pair.Key + " = " + pair.Value);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 2016-07-03
      • 2013-11-28
      • 1970-01-01
      • 2022-01-02
      • 2016-11-19
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多