aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.48k stars 466 forks source link

Support naming conventions for enum members #773

Open pardahlman opened 1 year ago

pardahlman commented 1 year ago

Is your feature request related to a problem? Please describe.

I have a YAML file where both properties and their values use snake case.

project:
    type: database_migration

The corresponding C# DTO uses enum

enum ProjectType
{
  DatabaseMigration
}

I have configred YamlDotNet to use UnderscoredNamingConvention, but the deserialization fails:

YamlDotNet.Core.YamlException: (Line: 4, Col: 11, Idx: 36) - (Line: 4, Col: 20, Idx: 45): Exception during deserialization
 ---> System.ArgumentException: Requested value 'database_migration' was not found.
   at System.Enum.TryParseByName(RuntimeType enumType, String originalValueString, ReadOnlySpan`1 value, Boolean ignoreCase, Boolean throwOnFailure, UInt64& result)
   at System.Enum.TryParseInt32Enum(RuntimeType enumType, String originalValueString, ReadOnlySpan`1 value, Int32 minInclusive, Int32 maxInclusive, Boolean ignoreCase, Boolean throwOnFailure, TypeCode type, Int32& result)
   at System.Enum.TryParse(Type enumType, String value, Boolean ignoreCase, Boolean throwOnFailure, Object& result)
   at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
   at YamlDotNet.Serialization.NodeDeserializers.ScalarNodeDeserializer.YamlDotNet.Serialization.INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object& value)

My initial analysis suggests that it's the call to Enum.Parse in ScalarNodeDeserializer that is performed with the underscored value (database_migration). Looking further into how INamingConvention is used, it appears that it's only used for property values (I might be wrong here!).

Describe the solution you'd like

I would like to deserialize YAML with snake case property values into C# enums defined in pascal case. It would be preferable if I could serialize C# DTOs using pascal case enums values into YAML with snake case property values (e.g. roundtrip).

Describe alternatives you've considered

Using a C# enum with snake case works, but is not desirable

enum ProjectType
{
  database_migration
}
EdwardCooke commented 1 year ago

I doubt it will work, but can you try the yamlmember attribute and set the alias property? I suspect it won’t though. If you want to implement that if it doesn’t we’re always open to pull requests.

pardahlman commented 1 year ago

Thanks for getting back on this. I'll take a look at yamlmember and get back to you if I find the time to implement this feature.

SlimeNull commented 1 year ago

This is indeed necessary.

aaubry commented 5 months ago

A fix for this issue has been released in version 15.1.0.