StringConverter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Buffers;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.Json;
  6. namespace Util
  7. {
  8. /// <summary>
  9. /// Json任何类型读取到字符串属性
  10. /// 因为 System.Text.Json 必须严格遵守类型一致,当非字符串读取到字符属性时报错:
  11. /// The JSON value could not be converted to System.String.
  12. /// </summary>
  13. public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>
  14. {
  15. public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  16. {
  17. if (reader.TokenType == JsonTokenType.String)
  18. {
  19. return reader.GetString();
  20. }
  21. else
  22. {
  23. //非字符类型,返回原生内容
  24. return GetRawPropertyValue(reader);
  25. }
  26. throw new JsonException();
  27. }
  28. public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
  29. {
  30. writer.WriteStringValue(value);
  31. }
  32. /// <summary>
  33. /// 非字符类型,返回原生内容
  34. /// </summary>
  35. /// <param name="jsonReader"></param>
  36. /// <returns></returns>
  37. private static string GetRawPropertyValue(Utf8JsonReader jsonReader)
  38. {
  39. ReadOnlySpan<byte> utf8Bytes = jsonReader.HasValueSequence ?
  40. jsonReader.ValueSequence.ToArray() :
  41. jsonReader.ValueSpan;
  42. return Encoding.UTF8.GetString(utf8Bytes);
  43. }
  44. }
  45. }