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")] 应用于任何枚举值。
以下是涉及的步骤:
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); }
public enum Example { Trick, Treat, [EnumMember(Value = "Trick-Or-Treat")] TrickOrTreat, }
var options = new JsonSerializerOptions { Converters = { new JsonEnumMemberStringEnumConverter() }, // Set other options as required: WriteIndented = true, }; var json = JsonSerializer.Serialize(values, options);
参考此答案Mani Gandham 提出问题,寻求如何做的指导
注释:
我希望这个解释有所帮助!如果您还有其他问题,请告诉我。
以上是如何为 System.Text.Json 中的枚举值指定自定义名称?的详细内容。更多信息请关注PHP中文网其他相关文章!