using System; using System.Text.Json; using System.Text.Json.Serialization; namespace Jellyfin.Extensions.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 TStruct : struct { /// public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // Token is empty string. if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || (!reader.HasValueSequence && reader.ValueSpan.IsEmpty))) { return null; } return JsonSerializer.Deserialize(ref reader, options); } /// public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options) => JsonSerializer.Serialize(writer, value!.Value, options); // null got handled higher up the call stack } }