2020-09-01 10:12:36 -04:00
|
|
|
|
using System;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
|
|
|
|
|
namespace MediaBrowser.Common.Json.Converters
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
2020-09-01 11:42:59 -04:00
|
|
|
|
/// Converts a nullable struct or value to/from JSON.
|
2020-09-01 10:12:36 -04:00
|
|
|
|
/// Required - some clients send an empty string.
|
|
|
|
|
/// </summary>
|
2020-09-27 11:45:11 -04:00
|
|
|
|
/// <typeparam name="TStruct">The struct type.</typeparam>
|
|
|
|
|
public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
|
|
|
|
|
where TStruct : struct
|
2020-09-01 10:12:36 -04:00
|
|
|
|
{
|
|
|
|
|
/// <inheritdoc />
|
2020-09-27 11:45:11 -04:00
|
|
|
|
public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
2020-09-01 10:12:36 -04:00
|
|
|
|
{
|
2020-09-27 11:45:11 -04:00
|
|
|
|
if (reader.TokenType == JsonTokenType.Null)
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Token is empty string.
|
2020-09-01 11:19:22 -04:00
|
|
|
|
if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
|
2020-09-01 10:12:36 -04:00
|
|
|
|
{
|
2020-09-01 11:19:22 -04:00
|
|
|
|
return null;
|
2020-09-01 10:12:36 -04:00
|
|
|
|
}
|
2020-09-01 11:19:22 -04:00
|
|
|
|
|
2020-09-27 11:45:11 -04:00
|
|
|
|
return JsonSerializer.Deserialize<TStruct>(ref reader, options);
|
2020-09-01 10:12:36 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
2020-09-27 11:45:11 -04:00
|
|
|
|
public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
|
2020-09-01 10:12:36 -04:00
|
|
|
|
{
|
2020-09-27 11:45:11 -04:00
|
|
|
|
if (value.HasValue)
|
|
|
|
|
{
|
|
|
|
|
JsonSerializer.Serialize(writer, value.Value, options);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
writer.WriteNullValue();
|
|
|
|
|
}
|
2020-09-01 10:12:36 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|