Getting started
editInstall the package
Add the Meziantou.Framework.Yaml package to your project:
dotnet package add Meziantou.Framework.YamlThe package also contains the source generator: no other package is needed for source generation.
The examples of this documentation omit the using directives. The serializer needs using Meziantou.Framework.Yaml; and the attributes using Meziantou.Framework.Yaml.Serialization;; see Namespaces for the others.
Serialize a class
Given this class:
public sealed class Product
{
public int Id { get; set; }
[YamlPropertyName("name")]
public string DisplayName { get; set; } = "";
public string[] Tags { get; set; } = [];
}YamlSerializer.Serialize writes an instance as YAML, and YamlSerializer.Deserialize reads it back:
var options = new YamlSerializerOptions
{
PropertyNamingPolicy = YamlNamingPolicy.KebabCaseLower,
};
var yaml = YamlSerializer.Serialize(new Product
{
Id = 1,
DisplayName = "Sample product",
Tags = ["new", "featured"],
}, options);
Assert.Equal("""
id: 1
name: Sample product
tags:
- new
- featured
""", yaml);
var product = YamlSerializer.Deserialize<Product>(yaml, options);
Assert.Equal("Sample product", product!.DisplayName);- The public properties are written in their declaration order. PropertyNamingPolicy converts their names, here to kebab case; [YamlPropertyName] sets the name of one property and wins over the policy.
- The array is written as a block sequence, indented under its key.
- Reading accepts the same options. A key that matches no property is skipped by default.
Read a document without a class
When you only need a few values, or the document has no fixed shape, load it as a tree of nodes instead:
var stream = YamlStream.Load(new StringReader("""
product:
id: 1
name: Sample product
"""));
var document = stream[0];
var root = (YamlMapping)document.Contents!;
var product = (YamlMapping)root["product"]!;
var name = ((YamlValue)product["name"]!).Value;
Assert.Equal("Sample product", name);A YamlStream holds every document of the text; each document contains mappings (YamlMapping), sequences (YamlSequence) and scalars (YamlValue). See Document object model.
Next steps
- Serialize and deserialize: files, streams and reusable options.
- Members and names and Output format: control the YAML you write.
- Source generation: serialize without reflection, for NativeAOT and trimming.
- Handling errors and Reading untrusted YAML.