不支持集合类型“Newtonsoft.Json.Linq.JObject”

Tom*_*Tom 3 c# asp.net-web-api asp.net-core

我在 .netcore 3.0 中编写了一个端点来返回数据,但最终在控制器中抛出以下错误。

错误发生在线上

return Ok(cityResponses);
Run Code Online (Sandbox Code Playgroud)

我可以在执行此行之前查看数据

System.NotSupportedException: The collection type 'Newtonsoft.Json.Linq.JObject' is not supported.
   at System.Text.Json.JsonPropertyInfoNotNullable`4.GetDictionaryKeyAndValueFromGenericDictionary(WriteStackFrame& writeStackFrame, String& key, Object& value)
   at System.Text.Json.JsonPropertyInfo.GetDictionaryKeyAndValue(WriteStackFrame& writeStackFrame, String& key, Object& value)
   at System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result)
Run Code Online (Sandbox Code Playgroud)

控制器

[HttpGet]
        [Route("cities")]
        public async Task<IActionResult> Cities()
        {
            var cities = await _cityInfoService.GetCities();

            var cityResponses =  MapCityResponse(cities);

            return Ok(cityResponses);
        }
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 9

错误消息已经在这里给了你一些提示:

\n
\n

System.NotSupportedException:不支持集合类型 \'Newtonsoft.Json.Linq.JObject\'。\nat System.Text.Json.JsonPropertyInfoNotNullable`4.GetDictionaryKeyAndValueFromGenericDictionary(WriteStackFrame& writeStackFrame, String& key, Object& value)

\n
\n

正如你所看到的,有一些Newtonsoft.Json.Linq命名空间,还有一个System.Text.Json命名空间。

\n

从 ASP.NET Core 3.0 开始,JSON 的默认序列化器从 Newtonsoft.Json 更改为 .NET Core 中内置的新序列化器:System.Text.Json。有非常详细的文档介绍了这两个序列化器之间的差异以及如何将代码迁移到 System.Text.Json。但这里的总结是 System.Text.Json 的设计\xe2\x80\x94比 Newtonsoft.Json 更受限制,并且它无法直接从这些或到这些JObjectJArray对象序列化。

\n

幸运的是,对于依赖 Newtonsoft.Json 行为或需要其部分灵活性的应用程序,有一种方法可以重新配置 ASP.NET Core 应用程序以继续使用 Newtonsoft.Json 进行 JSON 序列化。

\n

为此,您可以遵循ASP.NET Core 3.0 的迁移指南。本质上,您必须引用 NuGet 包Microsoft.AspNetCore.Mvc.NewtonsoftJson,然后AddNewtonsoftJson()在您的方法中调用 MVC 构建器ConfigureServices。例如:

\n
services.AddControllers()\n    .AddNewtonsoftJson();\n
Run Code Online (Sandbox Code Playgroud)\n

这将确保 Newtonsoft.Json 用于所有内置 JSON 序列化,因此您JObjectJArray用法应该继续有效。

\n