Search code examples
yamldeserializationyamldotnet

How to deserialize a list of key/value pair in yaml file with YamlDotNet


Hi I'm using YamlDotNet to deserialize a yml file like this:

name: element name
description: something to describe

parameters:
- firstKey: value1
- secondKey: value2

this is the .net class for deserialize:

class MyElement
{
    public string name { get; set; }
    public string description { get; set; }
    public ??? parameters { get; set; }
}

which type I can use to properly deserialize the parameters property to list an array of key/value pair? And what's the better way, next, to retreive the value using the key?

this is the C# code to deserialize:

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...
var deser = new DeserializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()).Build();
var reader = File.OpenText(pathToFileYml);
var data = deser.Deserialize<MyElement>(reader);    

Thanks in advance


Solution

  • Each key-value pair is a mapping with one entry in YAML (there is no separate structure for single key-value pairs). Hence, parameters should be List<Dictionary<string,string>>.

    If you want to simply be able to query the value of each key, you should drop the sequence and make it a single YAML mapping:

    parameters:
      firstKey: value1
      secondKey: value2
    

    This would deserialize to Dictionary<string,string> which you can then query about the values. However, the order of the parameters is lost then.

    If you need to preserve the order of parameters, you need to keep the YAML sequence containing the key-value pairs and deserialize into a OrderedDictionary<string,string> – afaik YamlDotNet does not support this directly, but you can use the original structure (List<Dictionary<string,string>>) and build up an OrderedDictionary from it.