【问题标题】:System.Text.Json converter get the entire string object [duplicate]System.Text.Json 转换器获取整个字符串对象 [重复]
【发布时间】:2022-01-13 23:18:56
【问题描述】:

因此,我的 NewtonJson 自定义转换器无法与 body api 调用一起使用。 (默认使用 System.Text.Json 进行转换)。

所以目前我有一个临时解决方案来编写一些包装器,这些包装器最终会调用 Newtonjson,直到 text.json 转换器被编写和测试。

我想要做的是将整个对象作为字符串读取并将其传递给牛顿转换器

我的 StartUp.cs

 services.AddControllers(options =>
        options.Filters.Add<ApiExceptionFilterAttribute>())
            .AddFluentValidation(x => x.AutomaticValidationEnabled = false)//ValidationBehaviour handle fluent validations.
            .AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                x.JsonSerializerOptions.Converters.Add(new SystemModelConverter());
                x.JsonSerializerOptions.IgnoreNullValues = true;
            });

我的转换器类

 public class SystemModelConverter : JsonConverter<ISystemModel>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return (typeToConvert.GetInterface(typeof(ISystemModel).Name) != null);
    }

    public override ISystemModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = new StringBuilder();
        while(reader.Read())
        {
            var str = reader.GetString();
            value.Append(str);
        }
        //passing the string along
        return Newtonsoft.Json.JsonConvert.DeserializeObject(value.ToString(), CoreExtensions.GetJsonSerializerSettings()) as ISystemModel;
    }

    public override void Write(Utf8JsonWriter writer, ISystemModel value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

【问题讨论】:

  • body api 调用是什么意思?根据您使用的技术,您可能会更换序列化程序?
  • 我怀疑您尝试从 Utf8JsonReader 提取原始 JSON 字符串以传递给您的 Newtonsoft 转换器所花费的时间比重写您的 Newtonsoft 转换器所花费的时间更多。

标签: c# json .net system.text.json


【解决方案1】:

看起来这行得通

 using (var jsonDocument = JsonDocument.ParseValue(ref reader))
        {
            var jsonText = jsonDocument.RootElement.GetRawText();
        }

Source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 2021-10-20
    • 2020-01-25
    • 2020-11-15
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2012-06-11
    相关资源
    最近更新 更多