Search code examples
c#asp.net-coreasp.net-web-apienums

Handling enums in post request body


I am creating an ASP.NET Core Web API.

I want a post body like:

{
"Name": "XYX",
"Status":"Waiting"
}

Status is an Enum:

public enum Status
{
    [Description("Waiting")]
    Waiting = 1,
    [Description("Occuring")]
    Occuring = 2,
    [Description("Stopping")]
    Stopping = 3,
}

What should I do so I that I don't get the error:

The JSON value could not be converted to PostgreSql.Enums.StatusEnum. Path:

P.S.: Tried what's mentioned here but it didn't work for me.


Solution

  • ASP.NET in .NET Core 3.0 removed the JSON.NET(Newtonsoft.Json) dependency (it is used in the link you've provided), so try using System.Text.Json's attributes: JsonStringEnumConverter and JsonConverterAttribute.

    UPD Was not able to reproduce the issue you mentioned in the comment:

    class MyClass
    {    
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public Status MyProperty { get; set; }
    
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public Status MyProperty1 { get; set; }
    }
    
    var serialized = JsonSerializer.Serialize(new MyClass
    {
        MyProperty = Status.Waiting,
        MyProperty1 = Status.Occuring
    }); // results in string containing {"MyProperty":"Waiting","MyProperty1":"Occuring"}
    
    var result = JsonSerializer.Deserialize<MyClass>(serialized); // all properties set
    

    Also please note that name of the Status value is used for serialization/deserialization not the value of Description attribute.