1

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://learn.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 :)

Jabrel
  • 13
  • 1
  • 1
  • 4
  • any indication of what the JSON looks like in this example? – Marc Gravell May 11 '21 at 14:42
  • Curious to know if it may be because S.T.Json is getting choked up during deserialization on the `node_id` and `full_name` in the **`template_repository`**... – Frank Alvaro May 11 '21 at 15:11
  • @MarcGravell I updated the question with the model summarized json – Jabrel May 11 '21 at 15:15
  • @FrankAlvaro Sorry, i don't undestand your comment. should it work like that? I'm starting on APIs :) – Jabrel May 11 '21 at 15:16
  • @Jabrel - apologies, it was more of a personal curiosity :D The suggestion by @mj1313 may be what you're looking for (FWIW, it appears something similar to `ReferenceLoopHandling.Ignore` in for S.T.Json had been thrown around for inclusion in NET 5, but never made it - maybe NET 6?) – Frank Alvaro May 12 '21 at 12:34
  • I can not explain any better than this answer : https://stackoverflow.com/questions/60197270/jsonexception-a-possible-object-cycle-was-detected-which-is-not-supported-this – JStevens Nov 01 '21 at 20:12

1 Answers1

1

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);
mj1313
  • 7,930
  • 2
  • 12
  • 32