Search code examples
c#asp.netjson.net-6.0nsjsonserialization

Stop Json From Cycle Serializing


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


Solution

  • 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;
                });