【问题标题】:How to tell JSON.NET StringEnumConverter to take DisplayName?如何告诉 JSON.NET StringEnumConverter 采用 DisplayName?
【发布时间】:2014-07-28 12:28:08
【问题描述】:

我有以下型号:

public enum Status
{
    [Display(Name = "Awaiting Approval")]
    AwaitingApproval,
    Rejected,
    Accepted,
}

我在这样的模型中使用这个枚举:

public class Docs
    {
        [Key]
        public int Id { get; set; }
        [JsonConverter(typeof(StringEnumConverter))]
        public Status Status { get; set; }
    }

现在这工作正常;序列化程序返回与枚举等效的字符串。我的问题是如何告诉 JSON.NET 采用 Display 属性而不是 string

【问题讨论】:

    标签: c# asp.net asp.net-web-api json.net


    【解决方案1】:

    您应该尝试使用[EnumMember] 而不是[Display]。您还可以将[JsonConverter] 属性放在枚举本身上。

    [JsonConverter(typeof(StringEnumConverter))]
    public enum Status
    {
        [EnumMember(Value = "Awaiting Approval")]
        AwaitingApproval,
        Rejected,
        Accepted,
    }
    

    JsonConverter 属性的 VB.NET 版本是:

    <Newtonsoft.Json.JsonConverter(GetType(Newtonsoft.Json.Converters.StringEnumConverter))>
    

    【讨论】:

    • 这似乎不支持 i18n 场景。您能否详细说明并解释这是否确实准确,或者是否有办法将屏幕上显示的文本国际化?
    • @RichardB 您可以将 DisplayAttribute 用于 i18n 场景。
    【解决方案2】:

    在 WebAPI 中,最好的选择是使用描述值全局转换 JSON 中的所有枚举字符串

    1. 在模型中使用这个命名空间using Newtonsoft.Json.Converters;

      public class Docs
      {
      [Key]
      public int Id { get; set; }
      [JsonConverter(typeof(StringEnumConverter))]
      public Status Status { get; set; }
      }
      
    2. 在枚举中使用这个命名空间using System.Runtime.Serialization; 对于枚举成员

      public enum Status
      {
      [EnumMember(Value = "Awaiting Approval")]
      AwaitingApproval,
      Rejected,
      Accepted,
      }
      
    3. 在 Global.asax 中添加此代码

          protected void Application_Start()
          {
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
      
          }
      

    它可以使用 WebAPI 在 JSON 中正常返回枚举。

    【讨论】:

      【解决方案3】:

      我试过这个并得到错误type or namespace enum member could not be found... 所以你们也可能会遇到这个错误,所以你需要使用

      using System.Runtime.Serialization;
      

      仍然出现此错误,然后添加如下引用:

      Right click on your project -> Add -> Reference.. -> Assemblies -> Mark System.Runtime.Serialization (i have 4.0.0.0 version ) -> Ok
      

      现在你可以这样继续:

      [JsonConverter(typeof(StringEnumConverter))]
      public enum Status
      {
          [EnumMember(Value = "Awaiting Approval")]
          AwaitingApproval,
          Rejected,
          Accepted,
      }
      

      【讨论】:

        猜你喜欢
        • 2011-11-17
        • 1970-01-01
        • 2015-03-27
        • 2021-05-12
        • 2014-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多