How to deserialize a YAML string with YAMLDotNet - C# snippets


yaml csharp snippet deserialization yamldotnet

Small, short, and sweet article of the day.

Let’s say you have a YAML string like this:

Root:
  - Id: 1
    Type: Aereal
    Plant: Banyan tree
  - Id: 2
    Type: Aerating
    Plant: Mangrove

[In case you’re the one manually creating the string, use https://jsonformatter.org/yaml-formatter, click on the little checkmark icon and it’ll validate that it’s correct. If it’s not, it’ll let you know what’s up. ]

Step 1: Create a Root class to parse.

public class Root
{
    public string Id { get; set; }

    public string Type { get; set; }

    public string Plant { get; set; }
}

Step 2: Create a Roots class that will contain the “Root” list.

public class Roots
{
    // Added "listof" because VS will throw an error if you name it the same as
    // the class. Make sure to name it better tho'! 
    public List<Root> ListOfRoots { get; set; }
}

Note: if you don’t create a root class, the deserialization won’t work.

Step 3: Create your deserialization method with YAMLDotNet.

public Roots GetRoots() 
{
    string yaml = 
        "Root: 
           - Id: 1 
             Type: Aereal 
             Plant: Banyan tree 
           - Id: 2 
             Type: Aerating 
             Plant: Mangrove";
    
    // this is all yaml dot net
    IDeserializer deserializer = new DeserializerBuilder().Build(); 
    Roots result = deserializer.Deserialize<Roots>(yaml);
    
    return result;
}

Voila! you should have your YAML string deserialized and ready to use.

In conclusion: the most important things to take note of are:

1) How valid and correct your YAML string is.

2) Your deserialization classes.