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) { if (reader.TokenType == JsonTokenType.Null) { return null; } // Token is empty string. if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty)) { return null; } return JsonSerializer.Deserialize(ref reader, options); } /// public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options) { if (value.HasValue) { JsonSerializer.Serialize(writer, value.Value, options); } else { writer.WriteNullValue(); } } } }