aboutsummaryrefslogtreecommitdiff
path: root/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
diff options
context:
space:
mode:
authorJoshua M. Boniface <joshua@boniface.me>2021-08-18 02:46:59 -0400
committerGitHub <noreply@github.com>2021-08-18 02:46:59 -0400
commit72d3f7020ad80ce1a53eeae8c5d57abeb22a4679 (patch)
treedd43e663838cdc7d99a4af565523df58ae23c856 /src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
parent7aef0fce444e6d8e06386553ec7ea1401a01bbb1 (diff)
parente5cbafdb6b47377052e0d638908ef96e30a997d6 (diff)
Merge branch 'master' into patch-2
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();
+ }
+ }
+ }
+}