From 9ddf550b43b3dcaa1129e369242bd664632bff03 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 1 Sep 2020 09:42:59 -0600 Subject: Simplify json converters --- .../Json/Converters/JsonNullableStructConverter.cs | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs (limited to 'MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs') 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 +{ + /// + /// Converts a nullable struct or value to/from JSON. + /// Required - some clients send an empty string. + /// + /// The struct type. + public class JsonNullableStructConverter : JsonConverter + where T : struct + { + private readonly JsonConverter _baseJsonConverter; + + /// + /// Initializes a new instance of the class. + /// + /// The base json converter. + public JsonNullableStructConverter(JsonConverter baseJsonConverter) + { + _baseJsonConverter = baseJsonConverter; + } + + /// + 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); + } + + /// + public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) + { + _baseJsonConverter.Write(writer, value, options); + } + } +} -- cgit v1.2.3