skip to Main Content

I’m trying to serialize an object in ASP.NET Core MVC Web API into a JSON before returning it to the user.
The object is from an EF Core database, and the controllers are generated using scaffolding with some include properties I’ve added which I’d like to preserve up to the custom MaxDepth I’ve set.
I understand that this was a feature added in System.Text.Json in .NET 6, and I’d like to avoid using Newtonsoft.Json.

After consulting the C# docs, this is what I’ve added in Program.cs to configure ReferenceHandler:

builder.Services.AddControllers()
    .AddJsonOptions(o =>
    {
        o.JsonSerializerOptions.ReferenceHandler
            = ReferenceHandler.IgnoreCycles;
        o.JsonSerializerOptions.MaxDepth = 5;
    });

However, after adding the following code to my Program.cs, I’m still getting the error when attempting to access the endpoint:

System.Text.Json.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 5. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Setting ReferenceHandler to Preserve does not work either:

System.Text.Json.JsonException: The object or value could not be serialized. Path: $.Asset.AssetOdometers.
 ---> System.InvalidOperationException: CurrentDepth (5) is equal to or larger than the maximum allowed depth of 5. Cannot write the next JSON object or array.

My GET endpoint is as follows:

        // GET: api/Pmtasks
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Pmtask>>> GetPmtasks()
        {
          if (_context.Pmtasks == null)
          {
              return NotFound();
          }
            return await _context.Pmtasks
                .Include(t => t.Asset)
                .Include(t => t.Task)
                .Include(t => t.PmscheduleType)
                .ToListAsync();
        }

3

Answers


  1. Looking at the second exception

    System.Text.Json.JsonException: The object or value could not be serialized. Path: $.Asset.AssetOdometers.
    —> System.InvalidOperationException: CurrentDepth (5) is equal to or larger than the maximum allowed depth of 5. Cannot write the next JSON object or array.

    I would try either setting the MaxDepth greater than 5 or removing it altogether.

    Login or Signup to reply.
  2. looks like you are passing an object with higher depth than the allowed in your configuration. try increasing the allowed depth or just remove o.JsonSerializerOptions.MaxDepth = 5; which will set it to its default which is 64.

    Login or Signup to reply.
  3. You could try to remove JsonSerializerOptions.MaxDepth = 5; or add JsonIgnore Property on the Asset,Task,PmscheduleType property to avoid the error.It may help if you could show the details of your data and clarify what you want

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search