Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a yaml string

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?

like image 781
max Avatar asked Sep 03 '14 17:09

max


People also ask

How do I read a YAML file?

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.

How do I read a YAML file in Java?

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.


1 Answers

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>.

like image 106
Antoine Aubry Avatar answered Sep 19 '22 00:09

Antoine Aubry