I'm trying to use YamlDotNet to deserialize an array of objects into C# classes based on the key of those objects.
I have YAML like this:
steps:
- launch:
name: application
- click:
name: button
repeat: 2
- setValue:
name: field
value: test
And then some C# classes / interfaces like this:
public class Runner
{
public IEnumerable<IStep> Steps { get; set; } = new List<IStep>();
}
public interface IStep
{
}
public class Launch : IStep
{
public string Name { get; set; } = string.Empty;
}
public class Click : IStep
{
public string Name { get; set; } = string.Empty;
public int Repeat { get; set; } = 1;
}
public class SetValue : IStep
{
public string Name { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
}
Using YamlDotNet, I was trying to deserialize using WithTypeDiscriminatingNodeDeserializer with a deserializer like this:
new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.WithTypeDiscriminatingNodeDeserializer((options) =>
{
Dictionary<string, Type> keyMappings = new()
{
{ "launch", typeof(Launch) },
{ "click", typeof(Click) },
{ "setValue", typeof(SetValue) },
};
options.AddUniqueKeyTypeDiscriminator<IStep>(keyMappings);
})
.Build();
But this fails with Error: Property 'launch' not found on type 'Models.Launch'. Based on the documentation for AddUniqueKeyTypeDiscriminator, this is correct behavior as those examples have properties with names equal to those keys, but I was hoping to avoid that unnecessary wrapping, how might I achieve that?