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

46 lines
1.4 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-27 08:45:11 -07:00
/// <typeparam name="TStruct">The struct type.</typeparam>
public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
where TStruct : struct
2020-09-01 07:12:36 -07:00
{
/// <inheritdoc />
2020-09-27 08:45:11 -07:00
public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
2020-09-01 07:12:36 -07:00
{
2020-09-27 08:45:11 -07:00
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
// Token is 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
2020-09-27 08:45:11 -07:00
return JsonSerializer.Deserialize<TStruct>(ref reader, options);
2020-09-01 07:12:36 -07:00
}
/// <inheritdoc />
2020-09-27 08:45:11 -07:00
public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
2020-09-01 07:12:36 -07:00
{
2020-09-27 08:45:11 -07:00
if (value.HasValue)
{
JsonSerializer.Serialize(writer, value.Value, options);
}
else
{
writer.WriteNullValue();
}
2020-09-01 07:12:36 -07:00
}
}
}