JsonNullableInt32Converter.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Buffers;
  3. using System.Buffers.Text;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace MediaBrowser.Common.Json.Converters
  7. {
  8. /// <summary>
  9. /// Converts a nullable int32 object or value to/from JSON.
  10. /// </summary>
  11. public class JsonNullableInt32Converter : 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. ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
  19. if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed)
  20. {
  21. return number;
  22. }
  23. var stringValue = reader.GetString().AsSpan();
  24. // value is null or empty, just return null.
  25. if (stringValue.IsEmpty)
  26. {
  27. return null;
  28. }
  29. if (int.TryParse(stringValue, out number))
  30. {
  31. return number;
  32. }
  33. }
  34. return reader.GetInt32();
  35. }
  36. /// <inheritdoc />
  37. public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
  38. {
  39. if (value is null)
  40. {
  41. writer.WriteNullValue();
  42. }
  43. else
  44. {
  45. writer.WriteNumberValue(value.Value);
  46. }
  47. }
  48. }
  49. }