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?
We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
Read YAML File as Map in Java The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream , Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student. yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With