Skip to content

JsonSubtypes does not respect naming strategy for discriminator property value #80

@egovova11

Description

@egovova11

Description

The issue occurs when naming strategy other than CamelCase is used.

Source/destination types

public enum EnumType
{
    EnumMemberOne,
    EnumMemberTwo
}

public interface IMyType
{
    EnumType EnumValue {get;}
}

public class MyTypeOne : IMyType
{
    public EnumType EnumValue => EnumType.EnumMemberOne;
}

public class MyTypeTwo : IMyType
{
    public EnumType EnumValue => EnumType.EnumMemberTwo;
}
var serializerSettings = new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
            {
                NamingStrategy = new SnakeCaseNamingStrategy(),
            },
    Converters = new List<JsonConverter>
    {
          new StringEnumConverter
            {
                NamingStrategy = new SnakeCaseNamingStrategy()
            },
          JsonSubtypesConverterBuilder
                .Of(typeof(IMyType), nameof(IMyType.EnumValue))
                .RegisterSubtype(typeof(MyTypeOne), EnumType.EnumMemberOne)
                .RegisterSubtype(typeof(MyTypeTwo), EnumType.EnumMemberTwo)
                .Build()
    }
}

Source/destination JSON

{"enum_value":"enum_member_one"}

Expected behavior

JSON is deserialized correctly with regard to naming strategy settings.

Actual behavior

Deserialization fails with the following message:

System.ArgumentException: Could not convert 'enum_member_one' to EnumType. ---> Newtonsoft.Json.JsonSerializationException: Error converting value "enum_member_one" to type 'Namespace.EnumType'. Path 'enum_value', line 1, position 13. ---> System.ArgumentException: Requested value 'enum_member_one' was not found.

Steps to reproduce

var json = "{\"enum_value\":\"enum_member_one\"}";
var result = JsonConvert.DeserializeObject<IMyType>(jsonValue, serializerSettings);

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions