Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell JSON.NET StringEnumConverter to take DisplayName?

Tags:

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?

like image 445
Irshu Avatar asked Jul 28 '14 12:07

Irshu


People also ask

How to set JsonProperty name in c#?

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.

How does the JsonProperty attribute affect JSON serialization?

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.

What is Stringenumconverter C#?

Converts an Enum to and from its name string value. Newtonsoft.Json. JsonConverter. Newtonsoft.Json.Converters.

Can a tuple be serialized?

Summary. Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo .


2 Answers

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))> 
like image 199
nsgocev Avatar answered Sep 30 '22 23:09

nsgocev


In WebAPI the best option is to globally convert all enum string in JSON with Description value

  1. 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; } } 
  2. In Enum use this namespace using System.Runtime.Serialization; for EnumMember

    public enum Status { [EnumMember(Value = "Awaiting Approval")] AwaitingApproval, Rejected, Accepted, } 
  3. 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.

like image 44
adnan Avatar answered Sep 30 '22 23:09

adnan