I am trying to use YamlDotNet to help me parse a config file. I have studies its documentation and found two ways:
The first approach is not particularly elegant (the code is messy). But it allows me to have extra "label: value" pairs in the input file. Anything extra is ignored. I can also use logic in my code to detect if any "label" is missing and skip trying to read its value.
The second approach is very elegant, and the code is very clean. However, it chokes on the extra "label: value" pairs. Also, if any expected "label: value" pair is missing in the input file, it also throws an exception.
I am looking for a way to use the second approach (calling Deserialize method) but allow it to work even if there is extra data in the input file, or something is missing.
I did not find an "Optional" attribute which I was hoping I could apply to the members of my object model.
Can someone educate me please if having optional nodes or extra unused nodes is possible when using Deserialize approach?
The second approach is actually possible. You need to do the following:
[DefaultValue(1)]
public double Priority { get; set; }
var deserializer = new DeserializerBuilder()
.IgnoreUnmatchedProperties()
.Build();
var deserialized = deserializer.Deserialize<T>(input);
I can't find any documentation on this configuration option but for me it works as intended. The only thing I could find is the PR where the feature was introduced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With