gpt4 book ai didi

C# - Web API - 将枚举序列化为带空格的字符串

转载 作者:可可西里 更新时间:2023-11-01 08:06:32 25 4
gpt4 key购买 nike

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

考虑以下代码:

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 Controller 发送序列化的 Foo 对象时,它们可能看起来像这样:

{
"Type" : "TypeTwo"
}

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

{
"Type" : "Type Two"
}

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

编辑:

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

最佳答案

尝试如下所示添加 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 的包才能使用它。

关于C# - Web API - 将枚举序列化为带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com