JsonNullableStructConverter.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Jellyfin.Extensions.Json.Converters
  5. {
  6. /// <summary>
  7. /// Converts a nullable struct or value to/from JSON.
  8. /// Required - some clients send an empty string.
  9. /// </summary>
  10. /// <typeparam name="TStruct">The struct type.</typeparam>
  11. public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
  12. where TStruct : struct
  13. {
  14. /// <inheritdoc />
  15. public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  16. {
  17. // Token is empty string.
  18. if (reader.TokenType == JsonTokenType.String
  19. && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty)
  20. || (!reader.HasValueSequence && reader.ValueSpan.IsEmpty)))
  21. {
  22. return null;
  23. }
  24. return JsonSerializer.Deserialize<TStruct>(ref reader, options);
  25. }
  26. /// <inheritdoc />
  27. public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
  28. => JsonSerializer.Serialize(writer, value!.Value, options); // null got handled higher up the call stack
  29. }
  30. }