2
0

JsonStringConverter.cs 1.1 KB

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