How to make JSON.NET StringEnumConverter use hyphen-separated casing

前端 未结 4 696
野性不改
野性不改 2020-12-08 13:26

I\'m consuming an api which returns string values like this. some-enum-value

I try to put these values in an enum, since the default StringEnumConverter

4条回答
  •  一生所求
    2020-12-08 13:52

    Also u can use this methods:

    public static string GetDescription(this Enum member)
            {
                if (member.GetType().IsEnum == false)
                    throw new ArgumentOutOfRangeException(nameof(member), "member is not enum");
    
                var fieldInfo = member.GetType().GetField(member.ToString());
    
                if (fieldInfo == null)
                    return null;
    
                var attributes = fieldInfo.GetCustomAttributes(false).ToList();
    
                return attributes.Any() ? attributes.FirstOrDefault()?.Description : member.ToString();
            }
    

    or

    public static string GetDescription(this object member)
            {
                var type = member.GetType();
    
                var attributes = type.GetCustomAttributes(false).ToList();
    
                return attributes.Any() ? attributes.FirstOrDefault()?.Description : member.GetType().Name;
            }
    

    and enum should have desctription attribute. Like this:

    public enum MyEnum
        {
            [Description("some-enum-value")]
            And,
            [Description("some-enum-value")]
            Or
    
        }
    

    And than you can use your enum like this:

    MyEnum.GetDescription(); //return "some-enum-value"
    

提交回复
热议问题