I've got the following model:
public enum Status { [Display(Name = "Awaiting Approval")] AwaitingApproval, Rejected, Accepted, }
I use this enum in a model like this:
public class Docs { [Key] public int Id { get; set; } [JsonConverter(typeof(StringEnumConverter))] public Status Status { get; set; } }
Now this works fine; the serializer returns the string equivalent of the enum. My question is how to tell JSON.NET to take the Display
attribute instead of the string
?
To set the name of individual properties, use the [JsonPropertyName] attribute. The property name set by this attribute: Applies in both directions, for serialization and deserialization.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
Converts an Enum to and from its name string value. Newtonsoft.Json. JsonConverter. Newtonsoft.Json.Converters.
Summary. Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo .
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))>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With