aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.54k stars 477 forks source link

YamlMember Alias usage #849

Closed oqo0 closed 1 year ago

oqo0 commented 1 year ago

I use YamlDotNet to read data from a config file like this:

ranks:
  - name: "Name"
    image-path: "assets/ranks/image1.png"
  - name: "Name"
    image-path: "assets/ranks/image2.png"

I try to deserialize it to a list of objects like this using IConfiguration:

public class Rank
{
    [YamlMember(Alias = "name")]
    public string Name { get; set; }

    [YamlMember(Alias = "image-path")]
    public string? Image { get; set; }
}
  builder.ConfigureAppConfiguration(options =>
  {
      options.AddYamlFile("config.yml", false);
  });
_ranks = _configuration.GetSection("ranks").Get<List<Rank>>();

When I read ranks from a configuration this way it doesn't work. Image property is always null. It looks like [YamlMember(Alias = "image-path")] is getting ignored when file is deserizlized.

I tried to change image-path property in my config to image like this

ranks:
  - name: "Name"
    image: "assets/ranks/image1.png"
  - name: "Name"
    image: "assets/ranks/image2.png"

And it works properly. Image property is getting deserialized to it's config value.

How can I fix this? Is there another attribute for deserialization?

I use YamlDotNet 13.3.1 net6.0

EdwardCooke commented 1 year ago

It could be the deserializerbuilder options that are set. Can you try deserializing it by itself without the configuration stuff?

something like var yaml=…. var deserializer = new DeserializerBuilder().Build(); var o = deserializer.Deserialize<List>(yaml);

What library/code are you using to add the yaml file to the configuration object?

oqo0 commented 1 year ago

I tried to deserializing it by itself and it didn't work without YamlMember attribute this time, but when I specified the Alias it worked.

Looks like you are right about deserializerbuilder options affecting this.

oqo0 commented 1 year ago

I'm using generic host configuration for adding yaml file to the config object:

    builder.ConfigureAppConfiguration(options =>
    {
        options.AddYamlFile("config.yml", false);
        options.AddYamlFile("language.yml", false);
    });

This is used for a Discord.NET bot which is not supported by generic host by default, so I use Discord.Addons.Hosting for this.

EdwardCooke commented 1 year ago

Since we've narrowed it down to whatever the library you are using to add the Yaml to your configuration is doing and not an issue with YamlDotNet, I'm going to close this issue.