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);
}
}
}