[英]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. 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
请求成功,但是在将 Json 转换为 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.
JsonException:检测到可能的 object 循环。 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.
这可能是由于循环或 object 深度大于最大允许深度 32。考虑在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 以支持循环。
I'd like to understand why the error occurs even with two simple properties with the same name as json我想了解为什么即使有两个与 json 同名的简单属性也会出现错误
GitHub Api Documentation https://docs.github.com/en/rest/reference/repos GitHub Api 文档https://docs.ZBF215181B5140522137B3D4F6/restB735.
documentation used as the basis for requesting the api: https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient#deserialize-the-json-result用作请求 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) Github 返回 Json (我隐藏了 json 的一些属性,因为有几个)
[
{
"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.我建议切换到 Newtonsoft.Json 来处理循环引用问题。
1.Install NewtonsoftJson package. 1.安装NewtonsoftJson package。
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
2.Add and configure it in ConfigureServices. 2.在ConfigureServices中添加并配置。
services.AddControllers().AddNewtonsoftJson(options=>
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
3.Use JsonConvert to Deserialize. 3.使用JsonConvert反序列化。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.