Skip to content
/ Michaël Hompus

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.

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.

website:
name: Blog
url: https://blog.hompus.nl

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

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

Deserializing

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

Serializing

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

website:
name: Blog
url: &o0
absolutePath: /
absoluteUri: *o0
localPath: /
authority: blog.hompus.nl
hostNameType: Dns
isDefaultPort: true
pathAndQuery: /
segments:
- /
host: blog.hompus.nl
port: 443
query: ""
fragment: ""
scheme: https
originalString: https://blog.hompus.nl
dnsSafeHost: blog.hompus.nl
idnHost: blog.hompus.nl
isAbsoluteUri: true
userInfo: ""

This was not what I expected.

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

YamlMember

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; }
[YamlMember(typeof(string))]
public Uri Url { get; set; }
}

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

website:
name: Blog
url: https://blog.hompus.nl/
Filed under C#
Last update: