c# - 使用 JSON.net 将枚举容器序列化为字符串

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

您可以通过添加属性将 WebAPI 模型中的枚举字段序列化为字符串:

enum Size
{
    Small,
    Medium,
    Large
}

class Example1
{
    [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    Size Size { get; set; }
}

这将序列化为这个 JSON:

{
  "Size": "Medium"
}

我怎样才能对枚举集合完成相同的操作?

class Example2
{
    IList<Size> Sizes { get; set; }
}

我想序列化为这个 JSON:

{
  "Sizes":
  [
    "Medium",
    "Large"
  ]
}

最佳答案

您需要使用 JsonPropertyAttribute.ItemConverterType属性:

class Example2
{
    [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
    public IList<Size> Sizes { get; set; }
}

关于c# - 使用 JSON.net 将枚举容器序列化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640162/

相关文章:

C# Newtonsoft.Json JObject 命名规范

c# - Newtonsoft JSON反序列化

json - 无法将 JSON 数组反序列化为 foo 类型

c# - 如何使用 .net 实现 SQL IN() 的等价物

c# - 如何声明具有匿名类型的字段 (C#)

c# - Microsoft Bot Framework,缺少子类型

c# - ModelBinder 验证在使用反射的 getter 上中断

internet-explorer - IE 中的 ASP.NET Web API

c# - 在 C# 中使用数据库值填充 ConcurrentDictionary 的锁定注意事项

asp.net - Ocelot 的文档 - 身份验证