diff options
| author | Niels van Velzen <nielsvanvelzen@users.noreply.github.com> | 2024-03-05 00:44:54 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-03-04 16:44:54 -0700 |
| commit | 407cf5d0bf9d3563ae77fd34ce29ffae5af4339f (patch) | |
| tree | 2640dfb680cc4f302ec2dbeeb2a7cd9536005b80 /src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs | |
| parent | 83d2bc3f9f13c62f6d3ef16c4fe75f0f5a18110d (diff) | |
Add MediaStreamProtocol enum (#10153)
* Add MediaStreamProtocol enum
* Add default handling for enum during deserialization
---------
Co-authored-by: Cody Robibero <cody@robibe.ro>
Diffstat (limited to 'src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs')
| -rw-r--r-- | src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs new file mode 100644 index 000000000..06ecfc558 --- /dev/null +++ b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs @@ -0,0 +1,49 @@ +using System; +using System.ComponentModel; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Jellyfin.Extensions.Json.Converters; + +/// <summary> +/// Json unknown enum converter. +/// </summary> +/// <typeparam name="T">The type of enum.</typeparam> +public class JsonDefaultStringEnumConverter<T> : JsonConverter<T> + where T : struct, Enum +{ + private readonly JsonConverter<T> _baseConverter; + + /// <summary> + /// Initializes a new instance of the <see cref="JsonDefaultStringEnumConverter{T}"/> class. + /// </summary> + /// <param name="baseConverter">The base json converter.</param> + public JsonDefaultStringEnumConverter(JsonConverter<T> baseConverter) + { + _baseConverter = baseConverter; + } + + /// <inheritdoc /> + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.IsNull() || reader.IsEmptyString()) + { + var customValueAttribute = typeToConvert.GetCustomAttribute<DefaultValueAttribute>(); + if (customValueAttribute?.Value is null) + { + throw new InvalidOperationException($"Default value not set for '{typeToConvert.Name}'"); + } + + return (T)customValueAttribute.Value; + } + + return _baseConverter.Read(ref reader, typeToConvert, options); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + _baseConverter.Write(writer, value, options); + } +} |
