APS.NET Core 5.0 Json任何类型读取到字符串属性The JSON value could not be converted to System.String.

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration)
  4. {
  5. Configuration = configuration;
  6. }
  7. public IConfiguration Configuration { get; }
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  10. public void ConfigureServices(IServiceCollection services)
  11. {
  12. //重写Json非字符串读取到对象字符串属性
  13. services.AddMvc().AddJsonOptions(opts =>
  14. {
  15. var stringConverter = new StringConverter();
  16. opts.JsonSerializerOptions.Converters.Add(stringConverter);
  17. });
  18. }
  19. }
  1. /// <summary>
  2. /// Json任何类型读取到字符串属性
  3. /// 因为 System.Text.Json 必须严格遵守类型一致,当非字符串读取到字符属性时报错:
  4. /// The JSON value could not be converted to System.String.
  5. /// </summary>
  6. public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>
  7. {
  8. public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  9. {
  10. if (reader.TokenType == JsonTokenType.String)
  11. {
  12. return reader.GetString();
  13. }
  14. else
  15. {//非字符类型,返回原生内容
  16. return GetRawPropertyValue(reader);
  17. }
  18. throw new JsonException();
  19. }
  20. public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
  21. {
  22. writer.WriteStringValue(value);
  23. }
  24. /// <summary>
  25. /// 非字符类型,返回原生内容
  26. /// </summary>
  27. /// <param name="jsonReader"></param>
  28. /// <returns></returns>
  29. private static string GetRawPropertyValue(Utf8JsonReader jsonReader)
  30. {
  31. ReadOnlySpan<byte> utf8Bytes = jsonReader.HasValueSequence ?
  32. jsonReader.ValueSequence.ToArray() :
  33. jsonReader.ValueSpan;
  34. return Encoding.UTF8.GetString(utf8Bytes);
  35. }
  36. }

因为ASP.NET Core 5.0 内置的System.Text.Json 转换必须严格规定类型一致,所以当为整数的值转换为字符串时会Json格式转换错误,所以必须用上面的代码处理下,重写字符串转换方法,让所有类型都可以存到对象的字符串属性。