| | 1 | | using System; |
| | 2 | | using System.ComponentModel; |
| | 3 | | using System.Reflection; |
| | 4 | | using System.Text.Json; |
| | 5 | | using System.Text.Json.Serialization; |
| | 6 | |
|
| | 7 | | namespace Jellyfin.Extensions.Json.Converters; |
| | 8 | |
|
| | 9 | | /// <summary> |
| | 10 | | /// Json unknown enum converter. |
| | 11 | | /// </summary> |
| | 12 | | /// <typeparam name="T">The type of enum.</typeparam> |
| | 13 | | public class JsonDefaultStringEnumConverter<T> : JsonConverter<T> |
| | 14 | | where T : struct, Enum |
| | 15 | | { |
| | 16 | | private readonly JsonConverter<T> _baseConverter; |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Initializes a new instance of the <see cref="JsonDefaultStringEnumConverter{T}"/> class. |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="baseConverter">The base json converter.</param> |
| 19 | 22 | | public JsonDefaultStringEnumConverter(JsonConverter<T> baseConverter) |
| | 23 | | { |
| 19 | 24 | | _baseConverter = baseConverter; |
| 19 | 25 | | } |
| | 26 | |
|
| | 27 | | /// <inheritdoc /> |
| | 28 | | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 29 | | { |
| 2136 | 30 | | if (reader.IsNull() || reader.IsEmptyString()) |
| | 31 | | { |
| 62 | 32 | | var customValueAttribute = typeToConvert.GetCustomAttribute<DefaultValueAttribute>(); |
| 62 | 33 | | if (customValueAttribute?.Value is null) |
| | 34 | | { |
| 0 | 35 | | throw new InvalidOperationException($"Default value not set for '{typeToConvert.Name}'"); |
| | 36 | | } |
| | 37 | |
|
| 62 | 38 | | return (T)customValueAttribute.Value; |
| | 39 | | } |
| | 40 | |
|
| 2074 | 41 | | return _baseConverter.Read(ref reader, typeToConvert, options); |
| | 42 | | } |
| | 43 | |
|
| | 44 | | /// <inheritdoc /> |
| | 45 | | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 46 | | { |
| 10 | 47 | | _baseConverter.Write(writer, value, options); |
| 10 | 48 | | } |
| | 49 | | } |