Search code examples
c#.net-corejson.net

JsonConvert.SerializeObject using an enum doesn't retrieve the EnumMember attribute value correctly


We are trying to retrieve the value from the EnumMember attribute applied to an Enum. Using the code below we get "\"South Carolina\"" but we need "South Carolina":

JsonConvert.SerializeObject(dto.State, new StringEnumConverter());

This the enum:

public enum State
{
    [EnumMember(Value = "South Carolina")] 
    South_Carolina
}

We tried without the StringEnumConverter as below, and we get the number 0:

JsonConvert.SerializeObject(dto.State);

Using .ToString() gives us "South_Carolina"


Solution

  • As I wrote in the comment this is correct behavior of serializer. You can use reflection to get the EnumMemberAttribute value. For example like this:

    public string? GetEnumMemberAttributeValue<T>(T enumVal) where T: System.Enum
    {
        var mi = typeof(T).GetMember(enumVal.ToString()).First();
        var attr = mi.GetCustomAttributes().OfType<EnumMemberAttribute>().FirstOrDefault();
        return attr != null ? attr.Value : null ;
    }
    
    Console.WriteLine(GetEnumMemberAttributeValue(State.South_Carolina)); // prints "South Carolina"
    

    You can improve this code at least by introducing caching.