JsonOmdbNotAvailableInt32Converter.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #nullable enable
  2. using System;
  3. using System.ComponentModel;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace MediaBrowser.Providers.Plugins.Omdb
  7. {
  8. /// <summary>
  9. /// Converts a string <c>N/A</c> to <c>string.Empty</c>.
  10. /// </summary>
  11. public class JsonOmdbNotAvailableInt32Converter : JsonConverter<int?>
  12. {
  13. /// <inheritdoc />
  14. public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. if (reader.TokenType == JsonTokenType.String)
  17. {
  18. var str = reader.GetString();
  19. if (str != null && str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
  20. {
  21. return null;
  22. }
  23. var converter = TypeDescriptor.GetConverter(typeToConvert);
  24. return (int?)converter.ConvertFromString(str);
  25. }
  26. return JsonSerializer.Deserialize<int>(ref reader, options);
  27. }
  28. /// <inheritdoc />
  29. public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
  30. {
  31. if (value.HasValue)
  32. {
  33. writer.WriteNumberValue(value.Value);
  34. }
  35. else
  36. {
  37. writer.WriteNullValue();
  38. }
  39. }
  40. }
  41. }