1

When I Want to serialize a list of class property to Json, my application stop and throw exception as follow (I am using .Net 6):

System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. at...

I found many topics in different sites and sources but as they suggested, I add following option to program.cs:

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

Above code didn't work and I add below code and then together:

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

But these options didin't work as well. And finally I tried to define MaxDepth to 1 but this error occurred again.

How we can stop Json Serializer from this error or force to serialize only depth 1 of received data and ignore navigation property? Is DTO class final solution?

thank you all

Hadi Mazareei
  • 31
  • 1
  • 7
  • 3
    Your error message is originated from System.Text.Json library not Newtonsoft.Json. Try to set those settings for System.Text.Json . – sam Aug 05 '22 at 13:20
  • Hello. it was my mistake. I found solution in "answered question" suggested for this question. I set this option in serializing method parameter and its ok. But how can I set this option globally for my project? thanks – Hadi Mazareei Aug 05 '22 at 14:41

1 Answers1

1

The error message shows that the code uses System.Text.Json. Instead of changing to Newtonsoft.Json for only the reason of this error, you can configure the serializer to ignore cycles:

services.AddControllers()
            .AddJsonOptions(options => {
               options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
               // In addition, you can limit the depth
               // options.MaxDepth = 4;
            });
Markus
  • 20,838
  • 4
  • 31
  • 55
  • Hello. This option doesn't work as well but when I set this option in serializing method parameter, I never get exception. – Hadi Mazareei Aug 05 '22 at 14:39