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

46 lines
1.4 KiB
C#
Raw Normal View History

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