JsonInt32Converter.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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 int32 object or value to/from JSON.
  10. /// </summary>
  11. public class JsonInt32Converter : 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. if (int.TryParse(reader.GetString(), out number))
  24. {
  25. return number;
  26. }
  27. }
  28. return reader.GetInt32();
  29. }
  30. /// <inheritdoc />
  31. public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
  32. {
  33. writer.WriteNumberValue(value);
  34. }
  35. }
  36. }