YamlDotNet Documentation

repository·master·Indexed 25 days ago

https://github.com/aaubry/yamldotnet

A YAML library for .NET providing low-level parsing and emitting, a high-level object model, and a serialization library for reading and writing objects to and from YAML streams. Supports .NET 8.0, .NET 10.0, .NET Standard 2.0/2.1, and .NET Framework 4.7.

Tokens
987
Snippets
3
Records
4
Agent score
34%

What's inside YamlDotNet

  1. Serialize an object to a YAML string

    master

    Use SerializerBuilder to configure and create a serializer. You can specify naming conventions, such as CamelCaseNamingConvention.Instance, to control how property names are formatted in the resulting YAML string.

    using YamlDotNet.Serialization;
    using YamlDotNet.Serialization.NamingConventions;
    
    var person = new Person
    {
        Name = "Abe Lincoln",
        Age = 25,
        HeightInInches = 6f + 4f / 12f,
        Addresses = new Dictionary<string, Address>{
            { "home", new  Address() {
                    Street = "2720  Sundown Lane",
                    City = "Kentucketsville",
                    State = "Calousiyorkida",
                    Zip = "99978",
                }},
            { "work", new  Address() {
                    Street = "1600 Pennsylvania Avenue NW",
                    City = "Washington",
                    State = "District of Columbia",
                    Zip = "20500",
                }},
        }
    };
    
    var serializer = new SerializerBuilder()
        .WithNamingConvention(CamelCaseNamingConvention.Instance)
        .Build();
    var yaml = serializer.Serialize(person);
    System.Console.WriteLine(yaml);
  2. Deserialize a YAML string to an object

    master

    Use DeserializerBuilder to configure and create a deserializer. Use .WithNamingConvention() to match the naming style of the source YAML (e.g., UnderscoredNamingConvention.Instance for snake_case keys). Use the .Deserialize<T>(string) method to convert the YAML string into a typed object.

    using YamlDotNet.Serialization;
    using YamlDotNet.Serialization.NamingConventions;
    
    var yml = @"
    name: George Washington
    age: 89
    height_in_inches: 5.75
    addresses:
      home:
        street: 400 Mockingbird Lane
        city: Louaryland
        state: Hawidaho
        zip: 99970
    ";
    
    var deserializer = new DeserializerBuilder()
        .WithNamingConvention(UnderscoredNamingConvention.Instance)  // see height_in_inches in sample yml 
        .Build();
    
    //yml contains a string containing your YAML
    var p = deserializer.Deserialize<Person>(yml);
    var h = p.Addresses["home"];
    System.Console.WriteLine($"{p.Name} is {p.Age} years old and lives at {h.Street} in {h.City}, {h.State}.");