JsonResult(object) causes “The collection type 

2020-05-31 08:53发布

I upgraded an existing ASP.NET Core 2.2 project to 3.0. I have a method that returns JSON which worked in 2.2, but in 3.0, it causes "The collection type 'Newtonsoft.Json.Linq.JToken' is not supported." at the return.

[HttpGet()]
public async Task<JsonResult> Get()
{
    var res = some class object in a third-party library;
    return new JsonResult(res);
}

I have searched Google and found that Microsoft has replaced Newtonsoft Json to System.Text.Json, but I have not explicitly used Newtonsoft Json. In the project's "Frameworks", I could see the Newtonsoft Json, and I removed it and the using Newtonsoft.Json.Linq statements, but the result was the same. How not to use Newtonsoft Json?

The error message is:

System.NotSupportedException: The collection type 'Newtonsoft.Json.Linq.JToken' is not supported.
   at System.Text.Json.JsonClassInfo.GetElementType(Type propertyType, Type parentType, MemberInfo memberInfo, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.CreateProperty(Type declaredPropertyType, Type runtimePropertyType, Type implementedPropertyType, PropertyInfo propertyInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.AddPolicyProperty(Type propertyType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type classType)
   at System.Text.Json.JsonPropertyInfo.get_ElementClassInfo()
   at System.Text.Json.JsonSerializer.HandleObject(JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteObject(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.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext context, JsonResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext context, JsonResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

PS: I have tried it with other types and got some similar exception messages for collection types. With that, I searched Google and found this open issue on .NET Core's GitHub. It seems like System.Text.JSon currently does not support collection types fully, and a workaround is just use the old Newtonsoft Json.

3条回答
小情绪 Triste *
2楼-- · 2020-05-31 09:30

Migrate from ASP.NET Core 2.2 to 3.0

  • Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson

  • Update Startup.ConfigureServices to call AddNewtonsoftJson: services.AddMvc().AddNewtonsoftJson();

查看更多
相关推荐>>
3楼-- · 2020-05-31 09:33

@sabiland answer helped me, small changes

  1. added in .csproj reference to NewtonsoftJson, as below

< PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />

  1. adde in Startup.cs, in method ConfigureServices, AddMvcCore

    services.AddMvcCore()
            .AddNewtonsoftJson();
    
查看更多
\"骚年 ilove
4楼-- · 2020-05-31 09:53

In .NET Core 3.1 based web applications if you are getting this error, the Nuget package you need to have is the same "Microsoft.AspNetCore.Mvc.NewtonsoftJson".

The code in the ConfigureServices method in the Startup class would look like

services.AddControllersWithViews().AddNewtonsoftJson();

Refer this link

查看更多
登录 后发表回答