web-dev-qa-db-fra.com

JsonResult (objet) provoque "Le type de collection 'Newtonsoft.Json.Linq.JToken' n'est pas pris en charge."

J'ai mis à niveau un projet ASP.NET Core 2.2 existant vers 3.0. J'ai une méthode qui renvoie JSON qui fonctionnait en 2.2, mais en 3.0, elle provoque "Le type de collection 'Newtonsoft.Json.Linq.JToken' n'est pas pris en charge." au retour.

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

J'ai recherché sur Google et constaté que Microsoft a remplacé Newtonsoft Json par System.Text.Json, mais je n'ai pas explicitement utilisé Newtonsoft Json. Dans les "Frameworks" du projet, je pouvais voir le Newtonsoft Json, et je l'ai supprimé et le using Newtonsoft.Json.Linq, mais le résultat était le même. Comment ne pas utiliser Newtonsoft Json?

Le message d'erreur est:

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: Je l'ai essayé avec d'autres types et j'ai reçu des messages d'exception similaires pour les types de collection. Avec cela, j'ai recherché Google et trouvé ce problème ouvert sur le GitHub de .NET Core . Il semble que System.Text.JSon actuellement ne prend pas complètement en charge les types de collection, et une solution de contournement consiste simplement à utiliser l'ancien Newtonsoft Json.

13
Damn Vegetables

Dans les applications Web basées sur .NET Core 3.1, si vous obtenez cette erreur, le package Nuget dont vous avez besoin est le même "Microsoft.AspNetCore.Mvc.NewtonsoftJson".

Le code de la méthode ConfigureServices dans la classe de démarrage ressemblerait à

services.AddControllersWithViews().AddNewtonsoftJson();

Référer ce lien

1
sm101