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中文網其他相關文章!