aaubry / YamlDotNet

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

Type descriminator keys and casing #857

Closed dazinator closed 10 months ago

dazinator commented 11 months ago

I followed the wiki example to configure type descriminator:

 var deserializer = new DeserializerBuilder()
            .WithNamingConvention(CamelCaseNamingConvention.Instance)
            .WithTypeDiscriminatingNodeDeserializer((o) =>
            {
                IDictionary<string, Type> valueMappings = new Dictionary<string, Type> { { "Swarm", typeof(SwarmTaskDefinition) } };
                o.AddKeyValueTypeDiscriminator<TaskDefinition>("Type", valueMappings);
            })
            .Build();

But notice that I am passing in "Type" as the descrimator key, but am also using CamelCaseNamingConvention - as such the deserialiser was erroring - saying it can't construct an abstract type (i.e the base type). It took me a while to figure out what was going on, so I wonder if there is a more elegant way to handle the matching of this key.

From the wiki example I should have twigged that there must have been a reason why you use the string literal "ObjectType" rather than nameof(BaseType.ObjectType) and now I know why ;-)

To Reproduce As above

EdwardCooke commented 11 months ago

I can change the wiki example to be something other than objecttype as the key so it is a little more clear. Is that what you are looking for?

dazinator commented 11 months ago

@EdwardCooke it just wasn't obvious when configuring which property name to match on, that casing would play a role in the match. It doesn't really matter whether the c# object property name is called "Type" "ObjectType" or something else, if your yaml deserialiser is using different casing to whats in the yaml, it won't match. Maybe just a comment to explain the property name is case sensitive would be beneficial ;-)

EdwardCooke commented 10 months ago

I'll do that when I get a minute.

EdwardCooke commented 10 months ago

Comment is added to the docs.