-
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- // This method gets called by the runtime. Use this method to add services to the container.
- // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
- public void ConfigureServices(IServiceCollection services)
- {
- //重写Json非字符串读取到对象字符串属性
- services.AddMvc().AddJsonOptions(opts =>
- {
- var stringConverter = new StringConverter();
- opts.JsonSerializerOptions.Converters.Add(stringConverter);
- });
- }
- }
- /// <summary>
- /// Json任何类型读取到字符串属性
- /// 因为 System.Text.Json 必须严格遵守类型一致,当非字符串读取到字符属性时报错:
- /// The JSON value could not be converted to System.String.
- /// </summary>
- public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>
- {
- public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
- {
-
- if (reader.TokenType == JsonTokenType.String)
- {
- return reader.GetString();
- }
- else
- {//非字符类型,返回原生内容
- return GetRawPropertyValue(reader);
- }
-
- throw new JsonException();
- }
-
- public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
- {
- writer.WriteStringValue(value);
- }
- /// <summary>
- /// 非字符类型,返回原生内容
- /// </summary>
- /// <param name="jsonReader"></param>
- /// <returns></returns>
- private static string GetRawPropertyValue(Utf8JsonReader jsonReader)
- {
- ReadOnlySpan<byte> utf8Bytes = jsonReader.HasValueSequence ?
- jsonReader.ValueSequence.ToArray() :
- jsonReader.ValueSpan;
- return Encoding.UTF8.GetString(utf8Bytes);
- }
- }
因为ASP.NET Core 5.0 内置的System.Text.Json 转换必须严格规定类型一致,所以当为整数的值转换为字符串时会Json格式转换错误,所以必须用上面的代码处理下,重写字符串转换方法,让所有类型都可以存到对象的字符串属性。