jellyfin/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs

45 lines
1.5 KiB
C#
Raw Normal View History

2020-09-01 07:12:36 -07:00
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
2020-09-01 08:42:59 -07:00
/// Converts a nullable struct or value to/from JSON.
2020-09-01 07:12:36 -07:00
/// Required - some clients send an empty string.
/// </summary>
2020-09-01 08:42:59 -07:00
/// <typeparam name="T">The struct type.</typeparam>
public class JsonNullableStructConverter<T> : JsonConverter<T?>
where T : struct
2020-09-01 07:12:36 -07:00
{
2020-09-01 08:42:59 -07:00
private readonly JsonConverter<T?> _baseJsonConverter;
2020-09-01 08:19:22 -07:00
/// <summary>
2020-09-01 08:42:59 -07:00
/// Initializes a new instance of the <see cref="JsonNullableStructConverter{T}"/> class.
2020-09-01 08:19:22 -07:00
/// </summary>
/// <param name="baseJsonConverter">The base json converter.</param>
2020-09-01 08:42:59 -07:00
public JsonNullableStructConverter(JsonConverter<T?> baseJsonConverter)
2020-09-01 08:19:22 -07:00
{
_baseJsonConverter = baseJsonConverter;
}
2020-09-01 07:12:36 -07:00
/// <inheritdoc />
2020-09-01 08:42:59 -07:00
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
2020-09-01 07:12:36 -07:00
{
2020-09-01 08:42:59 -07:00
// Handle empty string.
2020-09-01 08:19:22 -07:00
if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
2020-09-01 07:12:36 -07:00
{
2020-09-01 08:19:22 -07:00
return null;
2020-09-01 07:12:36 -07:00
}
2020-09-01 08:19:22 -07:00
return _baseJsonConverter.Read(ref reader, typeToConvert, options);
2020-09-01 07:12:36 -07:00
}
/// <inheritdoc />
2020-09-01 08:42:59 -07:00
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
2020-09-01 07:12:36 -07:00
{
2020-09-01 08:19:22 -07:00
_baseJsonConverter.Write(writer, value, options);
2020-09-01 07:12:36 -07:00
}
}
}