在升级.netsdk到6.0版本后出现The JSON value could not be converted to System.String.原因是我代码定义的类型是string,但是传参的时候写了int,
public override void ConfigureServices(ServiceConfigurationContext context)
{
//重写Json非字符串读取到对象字符串属性
context.Services.AddMvc().AddJsonOptions(opts =>
{
var stringConverter = new StringConverter();
opts.JsonSerializerOptions.Converters.Add(stringConverter);
});
}
新建stringConverter类
///
/// Json任何类型读取到字符串属性
/// 因为 System.Text.Json 必须严格遵守类型一致,当非字符串读取到字符属性时报错:
/// The JSON value could not be converted to System.String.
///
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);
}
}
标签:Core,String,APS,could,System,value,Json,字符串,读取
From: https://www.cnblogs.com/drivertobolin/p/17124387.html