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.
To represent this in my application, I created a simple POCO.
Deserializing
When deserializing the file, this works completely as expected. As you can see in the VSCode debugger:
Serializing
Now I want to serialize the object back to YAML. However, it ends up looking quite different than before.
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.
And when generated the YAML file again, it looks like how I intended it.