aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs
diff options
context:
space:
mode:
authorPatrick Barron <barronpm@gmail.com>2020-08-24 20:04:13 -0400
committerPatrick Barron <barronpm@gmail.com>2020-08-24 20:04:13 -0400
commit9fa4fff15d27769d01d7badfca2b769f068beff6 (patch)
tree54ec485a18b4fd9f679f66ada82a2fc31694c94d /MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs
parent98ed90c4a2d94dc75c4c284d695e752ee3c882d5 (diff)
parentec3104d2d2654c47dbf41171ab218f78ddbaed23 (diff)
Merge branch 'master' into event-rewrite-1
# Conflicts: # Emby.Dlna/Emby.Dlna.csproj # Emby.Dlna/Eventing/DlnaEventManager.cs # Emby.Dlna/Service/BaseService.cs # Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs # MediaBrowser.Controller/Subtitles/SubtitleDownloadEventArgs.cs
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs55
1 files changed, 55 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs b/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs
new file mode 100644
index 000000000..c1660fe76
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Buffers;
+using System.Buffers.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Converts a nullable int32 object or value to/from JSON.
+ /// </summary>
+ public class JsonNullableInt32Converter : JsonConverter<int?>
+ {
+ /// <inheritdoc />
+ public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
+ if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed)
+ {
+ return number;
+ }
+
+ var stringValue = reader.GetString().AsSpan();
+
+ // value is null or empty, just return null.
+ if (stringValue.IsEmpty)
+ {
+ return null;
+ }
+
+ if (int.TryParse(stringValue, out number))
+ {
+ return number;
+ }
+ }
+
+ return reader.GetInt32();
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
+ {
+ if (value is null)
+ {
+ writer.WriteNullValue();
+ }
+ else
+ {
+ writer.WriteNumberValue(value.Value);
+ }
+ }
+ }
+}