JsonNullableStructConverter.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace MediaBrowser.Common.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. if (reader.TokenType == JsonTokenType.Null)
  18. {
  19. return null;
  20. }
  21. // Token is empty string.
  22. if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
  23. {
  24. return null;
  25. }
  26. return JsonSerializer.Deserialize<TStruct>(ref reader, options);
  27. }
  28. /// <inheritdoc />
  29. public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
  30. {
  31. if (value.HasValue)
  32. {
  33. JsonSerializer.Serialize(writer, value.Value, options);
  34. }
  35. else
  36. {
  37. writer.WriteNullValue();
  38. }
  39. }
  40. }
  41. }