12

I want to parse yaml in c# in such a way that I get a List of Hashtables. I'm using YamlDotNet. Here is my code:

TextReader tr = new StringReader(txtRawData.Text);
var reader = new EventReader(new MergingParser(new Parser(tr)));
Deserializer des = new Deserializer(); ;
var result = des.Deserialize<List<Hashtable>>(tr);

It does not fail but gives me a null object.

My yaml is like:

- Label: entry
  Layer: x
  id: B35E246039E1CB70
- Ref: B35E246039E1CB70
  Label: Info
  Layer: x
  id: CE0BEFC7022283A6
- Ref: CE0BEFC7022283A6
  Label: entry
  Layer: HttpWebRequest
  id: 6DAA24FF5B777506

How do I parse my yaml and convert it to the desired type without having to implement it on my own?

max
  • 9,708
  • 15
  • 89
  • 144

1 Answers1

17

The YAML document in your question is badly formatted. Each key must have the same indentation as the previous one. Since you mention that the code does not fail, I will assume that the actual document that you are parsing is correctly formatted.

I was able to successfully parse the document using the following code:

var deserializer = new Deserializer();
var result = deserializer.Deserialize<List<Hashtable>>(new StringReader(yaml));
foreach (var item in result)
{
    Console.WriteLine("Item:");
    foreach (DictionaryEntry entry in item)
    {
        Console.WriteLine("- {0} = {1}", entry.Key, entry.Value);
    }
}

This fiddle shows that the code works. I have removed the second line from your code because it creates an object that is never used.

Also, the Hashtable is probably not what you want to use. Since generics have been introduced in .NET, it is much better to use a Dictionary. It has the benefit of being type safe. In this case, you could use Dictionary<string, string>.

Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74
  • thanks. I also corrected the yaml that I posted. You way works fine. – max Sep 04 '14 at 03:29
  • @antoine Is this still valid code? When I try this today with your latest stable release the Deserialize method (line 2 above) throws an exception stating it expected a SequenceStart but got a MappingStart. I know the YAML is good because your YamlStream loads it just fine. This List of Hashtable seemed interested and was curious to see how it translated YAML file. No worries if it isn't supported anymore or only works on very basic YAML files, I was just curious. – Rodney S. Foley Oct 29 '17 at 00:33