JsonStringConverter.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Buffers;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace MediaBrowser.Common.Json.Converters
  7. {
  8. /// <summary>
  9. /// Converter to allow the serializer to read strings.
  10. /// </summary>
  11. public class JsonStringConverter : JsonConverter<string?>
  12. {
  13. /// <inheritdoc />
  14. public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. return reader.TokenType switch
  17. {
  18. JsonTokenType.Null => null,
  19. JsonTokenType.String => reader.GetString(),
  20. _ => GetRawValue(reader)
  21. };
  22. }
  23. /// <inheritdoc />
  24. public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
  25. {
  26. writer.WriteStringValue(value);
  27. }
  28. private static string GetRawValue(Utf8JsonReader reader)
  29. {
  30. var utf8Bytes = reader.HasValueSequence
  31. ? reader.ValueSequence.ToArray()
  32. : reader.ValueSpan;
  33. return Encoding.UTF8.GetString(utf8Bytes);
  34. }
  35. }
  36. }