From ef725de75bb7f21e28038906ea27d51404c37353 Mon Sep 17 00:00:00 2001 From: Aeon Date: Thu, 26 Nov 2026 02:52:30 +0100 Subject: [PATCH 1/2] Added enum converter to respect EnumMemberAttribute --- .../Serialization/ElectronJson.cs | 2 +- .../EnumMemberStringEnumConverter.cs | 97 +++++++++++++++++++ .../Tests/EnumSerializationTests.cs | 88 +++++++++++++++++ 3 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs create mode 100644 src/ElectronNET.IntegrationTests/Tests/EnumSerializationTests.cs diff --git a/src/ElectronNET.API/Serialization/ElectronJson.cs b/src/ElectronNET.API/Serialization/ElectronJson.cs index 3fa06ddf..60706212 100644 --- a/src/ElectronNET.API/Serialization/ElectronJson.cs +++ b/src/ElectronNET.API/Serialization/ElectronJson.cs @@ -13,7 +13,7 @@ internal static class ElectronJson WriteIndented = false, Converters = { - new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) + new EnumMemberStringEnumConverter(JsonNamingPolicy.CamelCase) } }; } diff --git a/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs b/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs new file mode 100644 index 00000000..6d39cb3c --- /dev/null +++ b/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace ElectronNET.API.Serialization +{ + internal sealed class EnumMemberStringEnumConverter : JsonConverterFactory + { + private readonly JsonNamingPolicy namingPolicy; + + public EnumMemberStringEnumConverter(JsonNamingPolicy namingPolicy = null) + { + this.namingPolicy = namingPolicy; + } + + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert.IsEnum; + } + + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + var converterType = typeof(EnumConverter<>).MakeGenericType(typeToConvert); + return (JsonConverter) Activator.CreateInstance(converterType, namingPolicy); + } + + private sealed class EnumConverter : JsonConverter where TEnum : struct, Enum + { + private readonly Dictionary valueToName = new Dictionary(); + private readonly Dictionary nameToValue = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary fallbackNames = new ConcurrentDictionary(); + private readonly JsonNamingPolicy namingPolicy; + + public EnumConverter(JsonNamingPolicy namingPolicy) + { + this.namingPolicy = namingPolicy; + + foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)) + { + var value = (TEnum) field.GetValue(null); + var name = field.GetCustomAttribute()?.Value ?? field.GetCustomAttribute()?.Name ?? ConvertName(field.Name); + + valueToName.TryAdd(value, name); + nameToValue.TryAdd(name, value); + nameToValue.TryAdd(field.Name, value); + } + } + + public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.String: + var text = reader.GetString(); + if (text != null && nameToValue.TryGetValue(text, out var value)) + { + return value; + } + if (Enum.TryParse(text, true, out value)) + { + return value; + } + throw new JsonException($"Unable to convert \"{text}\" to enum {typeof(TEnum).Name}."); + case JsonTokenType.Number: + if (reader.TryGetInt64(out var number)) + { + return (TEnum)Enum.ToObject(typeof(TEnum), number); + } + break; + } + + throw new JsonException($"Unexpected token {reader.TokenType} when parsing enum {typeof(TEnum).Name}."); + } + + public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) + { + if (valueToName.TryGetValue(value, out var name)) + { + writer.WriteStringValue(name); + return; + } + + // Combined flags or undefined values: fall back to the default enum formatting. + writer.WriteStringValue(fallbackNames.GetOrAdd(value, v => ConvertName(v.ToString()))); + } + + private string ConvertName(string name) + { + return namingPolicy?.ConvertName(name) ?? name; + } + } + } +} diff --git a/src/ElectronNET.IntegrationTests/Tests/EnumSerializationTests.cs b/src/ElectronNET.IntegrationTests/Tests/EnumSerializationTests.cs new file mode 100644 index 00000000..8248b4e2 --- /dev/null +++ b/src/ElectronNET.IntegrationTests/Tests/EnumSerializationTests.cs @@ -0,0 +1,88 @@ +namespace ElectronNET.IntegrationTests.Tests +{ + using System.Text.Json; + using ElectronNET.API.Entities; + using ElectronNET.API.Serialization; + + // Vibrancy is macOS-only but serialization itself is platform-independent so the warning can be disabled for these tests + #pragma warning disable CA1416 + + public class EnumSerializationTests + { + private static readonly JsonSerializerOptions Options = ElectronJson.Options; + + [Theory] + [InlineData(Vibrancy.underWindow, "\"under-window\"")] + [InlineData(Vibrancy.underPage, "\"under-page\"")] + [InlineData(Vibrancy.appearanceBased, "\"appearance-based\"")] + [InlineData(Vibrancy.fullscreenUi, "\"fullscreen-ui\"")] + [InlineData(Vibrancy.sidebar, "\"sidebar\"")] + public void Serialize_Vibrancy_ShouldUseEnumMemberValue(Vibrancy value, string expected) + { + JsonSerializer.Serialize(value, Options).Should().Be(expected); + } + + [Fact] + public void Serialize_TitleBarStyleDefault_ShouldUseJsonPropertyName() + { + JsonSerializer.Serialize(TitleBarStyle.defaultStyle, Options).Should().Be("\"default\""); + } + + [Fact] + public void Serialize_UnannotatedMember_ShouldBeCamelCase() + { + JsonSerializer.Serialize(TitleBarStyle.hiddenInset, Options).Should().Be("\"hiddenInset\""); + JsonSerializer.Serialize(TitleBarStyle.customButtonsOnHover, Options).Should().Be("\"customButtonsOnHover\""); + } + + [Fact] + public void Serialize_BrowserWindowOptions_ShouldWriteAnnotatedEnumNames() + { + var options = new BrowserWindowOptions { Vibrancy = Vibrancy.underWindow }; + + var json = JsonSerializer.Serialize(options, Options); + + json.Should().Contain("\"vibrancy\":\"under-window\""); + json.Should().Contain("\"titleBarStyle\":\"default\""); + } + + [Fact] + public void Deserialize_CookieChangedCause_ShouldRoundTripJsonPropertyName() + { + JsonSerializer.Deserialize("\"expired_overwrite\"", Options).Should().Be(CookieChangedCause.expiredOverwrite); + JsonSerializer.Serialize(CookieChangedCause.expiredOverwrite, Options).Should().Be("\"expired_overwrite\""); + } + + [Theory] + [InlineData("\"under-window\"")] + [InlineData("\"underWindow\"")] + [InlineData("\"UnderWindow\"")] + public void Deserialize_Vibrancy_ShouldAcceptAnnotatedAndMemberNames(string json) + { + JsonSerializer.Deserialize(json, Options).Should().Be(Vibrancy.underWindow); + } + + [Fact] + public void Deserialize_IntegerValue_ShouldBeAccepted() + { + JsonSerializer.Deserialize(((int)Vibrancy.underWindow).ToString(), Options).Should().Be(Vibrancy.underWindow); + } + + [Fact] + public void Deserialize_UnknownName_ShouldThrow() + { + var act = () => JsonSerializer.Deserialize("\"not-a-vibrancy\"", Options); + + act.Should().Throw(); + } + + [Fact] + public void NullableEnum_ShouldRoundTrip() + { + JsonSerializer.Serialize(Vibrancy.underWindow, Options).Should().Be("\"under-window\""); + JsonSerializer.Serialize(null, Options).Should().Be("null"); + JsonSerializer.Deserialize("\"under-window\"", Options).Should().Be(Vibrancy.underWindow); + JsonSerializer.Deserialize("null", Options).Should().BeNull(); + } + } +} From 14c8e051482531a159e74272c66c0b194803b411 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 26 Nov 2026 13:02:31 +0100 Subject: [PATCH 2/2] Enhance enum serialization in EnumMemberStringEnumConverter Refactor enum serialization methods to improve handling of numeric values and property names. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../EnumMemberStringEnumConverter.cs | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs b/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs index 6d39cb3c..af2a8841 100644 --- a/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs +++ b/src/ElectronNET.API/Serialization/EnumMemberStringEnumConverter.cs @@ -66,16 +66,29 @@ public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe } throw new JsonException($"Unable to convert \"{text}\" to enum {typeof(TEnum).Name}."); case JsonTokenType.Number: - if (reader.TryGetInt64(out var number)) - { - return (TEnum)Enum.ToObject(typeof(TEnum), number); - } - break; + var underlyingType = Enum.GetUnderlyingType(typeof(TEnum)); + var numericValue = JsonSerializer.Deserialize(ref reader, underlyingType, options); + return (TEnum)Enum.ToObject(typeof(TEnum), numericValue); } throw new JsonException($"Unexpected token {reader.TokenType} when parsing enum {typeof(TEnum).Name}."); } + public override TEnum ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var text = reader.GetString(); + if (text != null && (nameToValue.TryGetValue(text, out var value) || Enum.TryParse(text, true, out value))) + { + return value; + } + throw new JsonException($"Unable to convert \"{text}\" to enum {typeof(TEnum).Name}."); + } + + public override void WriteAsPropertyName(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) + { + writer.WritePropertyName(valueToName.TryGetValue(value, out var name) ? name : fallbackNames.GetOrAdd(value, v => ConvertName(v.ToString()))); + } + public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) { if (valueToName.TryGetValue(value, out var name)) @@ -85,6 +98,13 @@ public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOpt } // Combined flags or undefined values: fall back to the default enum formatting. + var formatted = value.ToString(); + if (char.IsDigit(formatted[0]) || formatted[0] == '-') + { + var underlyingType = Enum.GetUnderlyingType(typeof(TEnum)); + JsonSerializer.Serialize(writer, Convert.ChangeType(value, underlyingType), underlyingType, options); + return; + } writer.WriteStringValue(fallbackNames.GetOrAdd(value, v => ConvertName(v.ToString()))); }