aboutsummaryrefslogtreecommitdiff
path: root/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
diff options
context:
space:
mode:
authorPatrick Barron <barronpm@gmail.com>2021-06-22 21:09:54 -0400
committerPatrick Barron <barronpm@gmail.com>2021-06-23 20:22:12 -0400
commitae878fa051e73dd1df90f1fed3ca5f7ad28b7beb (patch)
tree8d590d6ae9aea9a84626fa31695f0ed47969e33d /src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
parentf96722fa749b94b8affbf75da5d6941cab219a84 (diff)
parent94056049131a8573d7a4d0690da04c0e8bc240ad (diff)
Merge branch 'master' into authenticationdb-efcore
# Conflicts: # Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs # Emby.Server.Implementations/Session/SessionManager.cs # Jellyfin.Server.Implementations/Security/AuthorizationContext.cs
Diffstat (limited to 'src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs')
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
new file mode 100644
index 000000000..6de238b39
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
@@ -0,0 +1,45 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a nullable struct or value to/from JSON.
+ /// Required - some clients send an empty string.
+ /// </summary>
+ /// <typeparam name="TStruct">The struct type.</typeparam>
+ public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
+ where TStruct : struct
+ {
+ /// <inheritdoc />
+ public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.Null)
+ {
+ return null;
+ }
+
+ // Token is empty string.
+ if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
+ {
+ return null;
+ }
+
+ return JsonSerializer.Deserialize<TStruct>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
+ {
+ if (value.HasValue)
+ {
+ JsonSerializer.Serialize(writer, value.Value, options);
+ }
+ else
+ {
+ writer.WriteNullValue();
+ }
+ }
+ }
+}