首页 后端开发 C++ 如何为 System.Text.Json 中的枚举值指定自定义名称?

如何为 System.Text.Json 中的枚举值指定自定义名称?

Jan 14, 2025 am 10:37 AM

How to Specify Custom Names for Enum Values in System.Text.Json?

System.Text.Json:如何为枚举值指定自定义名称?

此功能不可用.NET Core 3.0、.NET 5、.NET 6.0、.NET 7.0 或 .NET 中的框8.0。因此,您需要创建自己的 JsonConverterFactory 来序列化具有属性指定的自定义值名称的枚举,或使用具有相同功能的 NuGet 包,例如 Macross.Json.Extensions。

如果您正在使用.NET 7或更高版本,或者早期版本中只需要序列化而不需要反序列化具有自定义名称的枚举,可以通过创建JsonConverterFactory 通过为每个枚举构造自定义的 JsonNamingPolicy 来适应 JsonStringEnumConverter,并将 [EnumMember(Value = "xxx")] 应用于任何枚举值。

以下是涉及的步骤:

  1. 创建自定义转换器:
public class JsonEnumMemberStringEnumConverter : JsonConverterFactory
{
    public JsonEnumMemberStringEnumConverter() : this(null, true) { }

    public JsonEnumMemberStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true)
    {
        this.namingPolicy = namingPolicy;
        this.allowIntegerValues = allowIntegerValues;
        this.baseConverter = new JsonStringEnumConverter(namingPolicy, allowIntegerValues);
    }

    public override bool CanConvert(Type typeToConvert) => baseConverter.CanConvert(typeToConvert);

    public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var query = from field in typeToConvert.GetFields(BindingFlags.Public | BindingFlags.Static)
                    let attr = field.GetCustomAttribute<EnumMemberAttribute>()
                    where attr != null && attr.Value != null
                    select (field.Name, attr.Value);
        var dictionary = query.ToDictionary(p => p.Item1, p => p.Item2);
        if (dictionary.Count > 0)
            return new JsonStringEnumConverter(new DictionaryLookupNamingPolicy(dictionary, namingPolicy), allowIntegerValues).CreateConverter(typeToConvert, options);
        else
            return baseConverter.CreateConverter(typeToConvert, options);
    }
}

public class JsonNamingPolicyDecorator : JsonNamingPolicy
{
    readonly JsonNamingPolicy? underlyingNamingPolicy;

    public JsonNamingPolicyDecorator(JsonNamingPolicy? underlyingNamingPolicy) => this.underlyingNamingPolicy = underlyingNamingPolicy;
    public override string ConvertName(string name) => underlyingNamingPolicy?.ConvertName(name) ?? name;
}

internal class DictionaryLookupNamingPolicy : JsonNamingPolicyDecorator
{
    readonly Dictionary<string, string> dictionary;

    public DictionaryLookupNamingPolicy(Dictionary<string, string> dictionary, JsonNamingPolicy? underlyingNamingPolicy) : base(underlyingNamingPolicy) => this.dictionary = dictionary ?? throw new ArgumentNullException();
    public override string ConvertName(string name) => dictionary.TryGetValue(name, out var value) ? value : base.ConvertName(name);
}
登录后复制
  1. 装饰你的枚举:
public enum Example
{
    Trick,
    Treat,
    [EnumMember(Value = "Trick-Or-Treat")]
    TrickOrTreat,
}
登录后复制
  1. 使用转换器Standalone:
var options = new JsonSerializerOptions
{
    Converters = { new JsonEnumMemberStringEnumConverter() },
    // Set other options as required:
    WriteIndented = true,
};
var json = JsonSerializer.Serialize(values, options);
登录后复制
  1. 使用 ASP.NET Core 注册转换器:

参考此答案Mani Gandham 提出问题,寻求如何做的指导

注释:

  • 在 .NET 6 及更早版本中,JsonStringEnumConverter 在反序列化期间忽略其命名策略;此问题已在拉取请求 73348 中修复。
  • 在 .Net Core 3.x 中,转换器可能无法按照 [Flags] 枚举的要求工作。此问题已在 .NET 5 中的问题 #31622 中修复。
  • 如果您需要在 .NET 6 或更早版本中使用自定义值名称来回传枚举,则需要从以下位置创建通用转换器转换器工厂
  • 另一种解决方案是使用 Macross.Json.Extensions 包中的 JsonStringEnumMemberConverter。安装包,然后使用属性 [JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumMemberConverter))].

我希望这个解释有所帮助!如果您还有其他问题,请告诉我。

以上是如何为 System.Text.Json 中的枚举值指定自定义名称?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章

仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
两个点博物馆:所有展览以及在哪里可以找到它们
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章

仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
两个点博物馆:所有展览以及在哪里可以找到它们
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章标签

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

c语言函数格式字母大小写转换步骤 c语言函数格式字母大小写转换步骤 Mar 03, 2025 pm 05:53 PM

c语言函数格式字母大小写转换步骤

Gulc:从头开始建造的C库 Gulc:从头开始建造的C库 Mar 03, 2025 pm 05:46 PM

Gulc:从头开始建造的C库

c语言函数返回值的类型有哪些?返回值是由什么决定的? c语言函数返回值的类型有哪些?返回值是由什么决定的? Mar 03, 2025 pm 05:52 PM

c语言函数返回值的类型有哪些?返回值是由什么决定的?

C标准模板库(STL)如何工作? C标准模板库(STL)如何工作? Mar 12, 2025 pm 04:50 PM

C标准模板库(STL)如何工作?

c语言函数的定义和调用规则是什么 c语言函数的定义和调用规则是什么 Mar 03, 2025 pm 05:53 PM

c语言函数的定义和调用规则是什么

c语言函数返回值在内存保存在哪里? c语言函数返回值在内存保存在哪里? Mar 03, 2025 pm 05:51 PM

c语言函数返回值在内存保存在哪里?

distinct用法和短语分享 distinct用法和短语分享 Mar 03, 2025 pm 05:51 PM

distinct用法和短语分享

如何有效地使用STL(排序,查找,转换等)的算法? 如何有效地使用STL(排序,查找,转换等)的算法? Mar 12, 2025 pm 04:52 PM

如何有效地使用STL(排序,查找,转换等)的算法?

See all articles