Skip to content

Using URI’s in YAML with YamlDotNet

Recently, I was using a YAML file for storing some data for a pet project. To work with this YAML in a .NET application, I use the excellent YamlDotNet library by Antoine Aubry.

One of my properties was a URL. Deserializing went fine, but when serializing back to a YAML file, things were not going as intended.

In this short article, I will explain how I did fix this.

The setup

I have a quite simple piece of YAML describing a website with a name and URL.

  name: Blog

To represent this in my application, I created a simple POCO.

public class Website {
    public string Name { get; set; }

    public Uri Url { get; set; }


When deserializing the file, this works completely as expected. As you can see in the VSCode debugger:

Deserialized data, as shown in the VSCode debugger
VSCode debugger showing the deserialized data


Now I want to serialize the object back to YAML. However, it ends up looking quite different than before.

  name: Blog
  url: &o0
    absolutePath: /
    absoluteUri: *o0
    localPath: /
    hostNameType: Dns
    isDefaultPort: true
    pathAndQuery: /
    - /
    port: 443
    query: ''
    fragment: ''
    scheme: https
    isAbsoluteUri: true
    userInfo: ''

This was not what I expected.

So how can we encourage YamlDotNet to store the property as a string?


The YamlMember attribute can solve this problem. It has the SerializeAs property that allows to set the Type that the serialize must use during serialization.

For this situation, I choose the String type.

public class Website {
    public string Name { get; set; }

    public Uri Url { get; set; }

And when generated the YAML file again, it looks like how I intended it.

  name: Blog