Search code examples
c#yamldotnet

How do I parse only part of YAML using YamlDotNet?


Suppose I have the following YAML:

config_one:
  name: foo
  stuff: value

config_two:
  name: bar
  random: value

I want to selectively parse config_one into an object and I want config_two to be ignored:

class ConfigOne
{
  public string Name {get;set;}
  public string Stuff {get;set;}
}

How can I do this? The documentation is pretty lacking, or at least, it uses a lot of terminology that doesn't make much sense to me, and thus I was not able to search for this functionality.


Solution

  • When building your deserializer, add IgnoreUnmatchedProperties():

    var deserializer = new DeserializerBuilder()
        .WithNamingConvention(UnderscoredNamingConvention.Instance)
        .IgnoreUnmatchedProperties()
        .Build();
    

    This "Instructs the deserializer to ignore unmatched properties instead of throwing an exception."
    Git Source