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

在升级.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);
    }
}

posted @ 2023-02-15 19:12  搭车去柏林  阅读(1060)  评论(0)    收藏  举报