Skip to content
Antoine Aubry edited this page Jul 17, 2019 · 3 revisions

YamlDotNet Serialization

Serialization is the process of converting an object graph into a YAML document. Later, that document can be deserialized to reconstruct an object graph equivalent to the original.

As an example, consider the following C# code, that creates an instance of a receipt:

var address = new Address
{
    street = "123 Tornado Alley\nSuite 16",
    city = "East Westville",
    state = "KS"
};

var receipt = new Receipt
{
    receipt = "Oz-Ware Purchase Invoice",
    date = new DateTime(2007, 8, 6),
    customer = new Customer
    {
        given = "Dorothy",
        family = "Gale"
    },
    items = new Item[]
    {
        new Item
        {
            part_no = "A4786",
            descrip = "Water Bucket (Filled)",
            price = 1.47M,
            quantity = 4
        },
        new Item
        {
            part_no = "E1628",
            descrip = "High Heeled \"Ruby\" Slippers",
            price = 100.27M,
            quantity = 1
        }
    },
    bill_to = address,
    ship_to = address,
    specialDelivery = "Follow the Yellow Brick\n" +
                        "Road to the Emerald City.\n" +
                        "Pay no attention to the\n" +
                        "man behind the curtain."
};

After serializing this graph, the resulting YAML document would be:

receipt: Oz-Ware Purchase Invoice
date: 2007-08-06T00:00:00.0000000
customer:
  given: Dorothy
  family: Gale
items:
- part_no: A4786
  descrip: Water Bucket (Filled)
  price: 1.47
  quantity: 4
- part_no: E1628
  descrip: High Heeled "Ruby" Slippers
  price: 100.27
  quantity: 1
bill_to: &address
  street: >-
    123 Tornado Alley

    Suite 16
  city: East Westville
  state: KS
ship_to: *address
specialDelivery: >-
  Follow the Yellow Brick

  Road to the Emerald City.

  Pay no attention to the

  man behind the curtain.

Because they have different dependencies, and keeping in line with the Single Responsibility Principle, serialization and deserialization services are provided by different classes, named Serializer and Deserializer, respectively.