JsonNullableStructConverter.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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="T">The struct type.</typeparam>
  11. public class JsonNullableStructConverter<T> : JsonConverter<T?>
  12. where T : struct
  13. {
  14. private readonly JsonConverter<T?> _baseJsonConverter;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="JsonNullableStructConverter{T}"/> class.
  17. /// </summary>
  18. /// <param name="baseJsonConverter">The base json converter.</param>
  19. public JsonNullableStructConverter(JsonConverter<T?> baseJsonConverter)
  20. {
  21. _baseJsonConverter = baseJsonConverter;
  22. }
  23. /// <inheritdoc />
  24. public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  25. {
  26. // Handle empty string.
  27. if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
  28. {
  29. return null;
  30. }
  31. return _baseJsonConverter.Read(ref reader, typeToConvert, options);
  32. }
  33. /// <inheritdoc />
  34. public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
  35. {
  36. _baseJsonConverter.Write(writer, value, options);
  37. }
  38. }
  39. }