Can't get enum to convert to json properly using Json.NET

前端 未结 3 505
旧巷少年郎
旧巷少年郎 2020-12-06 04:52

I have an enum:

public enum Animal 
{ 
    Dog, 
    Cat, 
    BlackBear 
}

I need to send it to a third-party API. This API requires that

相关标签:
3条回答
  • 2020-12-06 05:04
    // Might return null, better to use try catch
    public static Animals GetEnum(string val)
    {
        return (Animals)Enum.Parse(typeof(Animals), val, true);
    }
    
    public static string GetName(Animals an)
    {
        return Enum.GetName(typeof(Animals), an);
    }
    
    public static string GetReplace(Animals an)
    {
        var get = GetName(an);
        var tempstr = "";
        int getch = 0;
        foreach (var chr in get.ToCharArray())
        {
            if (chr == chr.ToUpper())
            {
                getch++;
                // Second up value char
                if (getch == 2)
                {
                    tempstr += "_" + chr;
                }
                else
                {
                    tempstr += chr;
                }
            }
            else
            {
                 tempstr += chr;
            }
        }
        return tempstr;
    }
    
    0 讨论(0)
  • 2020-12-06 05:18

    I think your ConConvert() implementation is not correct. It should be:

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Animals);
    }
    
    0 讨论(0)
  • 2020-12-06 05:29

    You don't need to write your own converter. Json.NET's StringEnumConverter will read the EnumMember attribute. If you change your enum to this, it will serialize from and to the values you want.

    [JsonConverter(typeof(StringEnumConverter))]
    public enum Animals 
    {
        [EnumMember(Value = "dog")]
        Dog, 
        [EnumMember(Value = "cat")]
        Cat, 
        [EnumMember(Value = "black_bear")]
        BlackBear 
    }
    

    (As a minor note, since Animals isn't a flags enum, it should be singular: Animal. You should consider changing it to this.)

    0 讨论(0)
提交回复
热议问题