aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
diff options
context:
space:
mode:
authorBond-009 <bond.009@outlook.com>2020-09-01 21:41:46 +0200
committerGitHub <noreply@github.com>2020-09-01 21:41:46 +0200
commit506fc7cbaeb8f82716f84b125ac598ff740bf552 (patch)
tree2693727c9103659e555d99f9178e3e33e9656930 /MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
parent2d198292a3ff1a5d213c9dd4643eee6ddef2661e (diff)
parent9ddf550b43b3dcaa1129e369242bd664632bff03 (diff)
Merge pull request #4033 from crobibero/empty-string-nullable-number
Readd nullable number converters
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs44
1 files changed, 44 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
new file mode 100644
index 000000000..cffc41ba3
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
@@ -0,0 +1,44 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Converts a nullable struct or value to/from JSON.
+ /// Required - some clients send an empty string.
+ /// </summary>
+ /// <typeparam name="T">The struct type.</typeparam>
+ public class JsonNullableStructConverter<T> : JsonConverter<T?>
+ where T : struct
+ {
+ private readonly JsonConverter<T?> _baseJsonConverter;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonNullableStructConverter{T}"/> class.
+ /// </summary>
+ /// <param name="baseJsonConverter">The base json converter.</param>
+ public JsonNullableStructConverter(JsonConverter<T?> baseJsonConverter)
+ {
+ _baseJsonConverter = baseJsonConverter;
+ }
+
+ /// <inheritdoc />
+ public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ // Handle empty string.
+ if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
+ {
+ return null;
+ }
+
+ return _baseJsonConverter.Read(ref reader, typeToConvert, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
+ {
+ _baseJsonConverter.Write(writer, value, options);
+ }
+ }
+}