JsonNullableInt64Converter.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace MediaBrowser.Common.Json.Converters
  5. {
  6. /// <summary>
  7. /// Parse JSON string as nullable long.
  8. /// Javascript does not support 64-bit integers.
  9. /// Required - some clients send an empty string.
  10. /// </summary>
  11. public class JsonNullableInt64Converter : JsonConverter<long?>
  12. {
  13. /// <summary>
  14. /// Read JSON string as int64.
  15. /// </summary>
  16. /// <param name="reader"><see cref="Utf8JsonReader"/>.</param>
  17. /// <param name="type">Type.</param>
  18. /// <param name="options">Options.</param>
  19. /// <returns>Parsed value.</returns>
  20. public override long? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
  21. {
  22. switch (reader.TokenType)
  23. {
  24. case JsonTokenType.String when (reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty:
  25. case JsonTokenType.Null:
  26. return null;
  27. default:
  28. // fallback to default handling
  29. return reader.GetInt64();
  30. }
  31. }
  32. /// <summary>
  33. /// Write long to JSON long.
  34. /// </summary>
  35. /// <param name="writer"><see cref="Utf8JsonWriter"/>.</param>
  36. /// <param name="value">Value to write.</param>
  37. /// <param name="options">Options.</param>
  38. public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
  39. {
  40. if (value is null)
  41. {
  42. writer.WriteNullValue();
  43. }
  44. else
  45. {
  46. writer.WriteNumberValue(value.Value);
  47. }
  48. }
  49. }
  50. }