FyreeW FyreeW - 1 year ago 428
YAML Question

Trying to convert YAML file to hashtable using yamldotnet

Right now I am trying to convert a YAML file into a hash table, utilizing the Deserializer that is provided in the YamlDotNet library. Getting the error

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

The YAML file structure looks like


Key1: Value1
Key2: Value2
Key3: Value3

Sometimes containing more than one section.

I have tried a solution similar to this Seeking guidance reading .yaml files with C# as well, however the same error occurs. How do I properly read in a YAML file, and convert it into a hash using YamlDotNet?

Answer Source

You are trying to deserialize your YAML input as a list:

//            ^^^^

But the uppermost object in your YAML file is a mapping (starting with Title:). This is why you get the error.

Your structure has four levels. The top level maps a string (Title) to the second level. The second level maps a string (Section1) to the third level. The third level maps strings (Key1) to strings (Value1).

Therefore, you should deserialize to something like:

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

If your uppermost object always has only one key-value pair (with Title as the key), you can instead write a class:

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

And then use deserialize to this class:

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