JsonOmdbNotAvailableInt32Converter.cs 1.3 KB

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