How to tell JSON.NET StringEnumConverter to take DisplayName?

不羁岁月 提交于 2019-12-20 10:27:10

问题


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?


回答1:


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,
}



回答2:


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.




回答3:


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,
}


来源:https://stackoverflow.com/questions/24995278/how-to-tell-json-net-stringenumconverter-to-take-displayname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!