【问题标题】:C# - Web API - Serializing Enums as strings with spacesC# - Web API - 将枚举序列化为带空格的字符串
【发布时间】:2015-10-22 10:33:26
【问题描述】:

我的问题很简单,但比其他与将枚举类型序列化为字符串相关的问题更具体一些。

考虑以下代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public enum MyEnum
{
    TypeOne,
    TypeTwo,
    TypeThree
}

public class Foo
{
   [JsonConverter(typeof(StringEnumConverter))]
   public MyEnum Types { get; set; }
}

当 Web API 控制器发送序列化的 Foo 对象时,它们可能看起来像这样:

{
    "Type" : "TypeTwo"
}

我的问题:是否可以将序列化的枚举作为每个大写字母前带有空格的字符串发送?这样的解决方案会生成这样的 JSON:

{
    "Type" : "Type Two"
}

如果需要任何其他信息来解决我的问题,请告诉我。谢谢!

编辑:

最好将枚举仅转换为带空格的字符串,同时将它们序列化为 JSON。我想在后端使用MyEnum.ToString() 时排除空格。

【问题讨论】:

  • 添加一个 EnumMemberAttribute [EnumMember("Type Two")] 有什么作用吗? github 上 StringEnumConverter 的源代码似乎利用了它。
  • 我不确定,但您认为使用该属性会对每个MyEnum.ToString() 方法产生影响吗?

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


【解决方案1】:

尝试如下图添加EnumMember,

[JsonConverter(typeof(StringEnumConverter))]
public enum MyEnum
{
    [EnumMember(Value = "Type One")]
    TypeOne,
    [EnumMember(Value = "Type Two")]
    TypeTwo,
    [EnumMember(Value = "Type Three")]
    TypeThree
}

您可能需要安装来自 Microsoft 的名为 System.Runtime.Serialization.Primitives 的包才能使用它。

【讨论】:

  • 这行得通!为了澄清我的编辑,这将影响 JSON 序列化。谢谢!
  • 这个 (stackoverflow.com/a/19768223/530933) 也可能有帮助。枚举顶部的[JsonConverter(typeof(StringEnumConverter))]
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 2020-03-24
  • 2013-12-13
  • 2019-11-28
  • 1970-01-01
  • 2011-01-08
  • 1970-01-01
相关资源
最近更新 更多