1

现在我正在尝试使用 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 guide reading .yaml files with C#的解决方案,但是会发生相同的错误。如何正确读取 YAML 文件,并使用 YamlDotNet 将其转换为哈希?

4

1 回答 1

3

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

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

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

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

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

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

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

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);
    }
}
于 2016-07-13T09:00:50.270 回答