I\'ve got the following model:
public enum Status
{
[Display(Name = \"Awaiting Approval\")]
AwaitingApproval,
Rejected,
Accepted,
}
You should try using [EnumMember]
instead of [Display]
. You can also put the [JsonConverter]
attribute on the enum itself.
[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
[EnumMember(Value = "Awaiting Approval")]
AwaitingApproval,
Rejected,
Accepted,
}
The VB.NET version for the JsonConverter attribute is:
<Newtonsoft.Json.JsonConverter(GetType(Newtonsoft.Json.Converters.StringEnumConverter))>
I tried this and got the error type or namespace enum member could not be found...
So you guys might get this error too so you need to use
using System.Runtime.Serialization;
and still you get this error then add a reference like below:
Right click on your project -> Add -> Reference.. -> Assemblies -> Mark System.Runtime.Serialization (i have 4.0.0.0 version ) -> Ok
Now you can proceed like this:
[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
[EnumMember(Value = "Awaiting Approval")]
AwaitingApproval,
Rejected,
Accepted,
}
In WebAPI the best option is to globally convert all enum string in JSON with Description value
In Model use this namespace using Newtonsoft.Json.Converters;
public class Docs
{
[Key]
public int Id { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public Status Status { get; set; }
}
In Enum use this namespace using System.Runtime.Serialization;
for EnumMember
public enum Status
{
[EnumMember(Value = "Awaiting Approval")]
AwaitingApproval,
Rejected,
Accepted,
}
In Global.asax add this code
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
}
It will work fine return enum in JSON using WebAPI.