简体   繁体   中英

Error when deserialize Json .NET CORE 5 - JsonException: A possible object cycle was detected which is not supported

Basically I created a API Project on .NET 5. My idea was to get some Repositories informations on the GitHub API and then disponibilize some informations in MY API. The request is sucessfull but, but the same error always occurs when converting Json to object

RepositoriesController:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class RepositoriesController : ControllerBase
{
    private static readonly HttpClient client = new HttpClient();

    private readonly ILogger<RepositoriesController> _logger;

    public RepositoriesController(ILogger<RepositoriesController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IActionResult Get(string number)
    {
        return Ok(ProcessRepositories());
    }

    private static async Task ProcessRepositories()
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
        client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");

        var streamTask = client.GetStreamAsync("https://api.github.com/orgs/dotnet/repos?sort=created&per_page=5&direction=desc");
        var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);
    }
}

Classe repository:

 public class Repository
{
    public string full_name { get; set; }
    public string node_id { get; set; }
    //public string description { get; set; }
}

But always on this part:

        var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);

The browser return this error:

JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

I'd like to understand why the error occurs even with two simple properties with the same name as json

GitHub Api Documentation https://docs.github.com/en/rest/reference/repos

documentation used as the basis for requesting the api: https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient#deserialize-the-json-result

Github Returned Json (I hid some properties of json because there are several)

[
    {
        "id": 1296269,
        "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
        "name": "Hello-World",
        "full_name": "octocat/Hello-World",
        [... several hidden properties for display purposes]
    }
]

Thanks in Advance:)

I suggest to switch to the Newtonsoft.Json to handle the circular references problem.

1.Install NewtonsoftJson package.

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

2.Add and configure it in ConfigureServices.

services.AddControllers().AddNewtonsoftJson(options=>
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

3.Use JsonConvert to Deserialize.

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");

var streamTask = await client.GetStringAsync("https://api.github.com/orgs/dotnet/repos?sort=created&per_page=5&direction=desc");
var repositories = JsonConvert.DeserializeObject<List<Repository>>(streamTask);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM