How to solve: Json Exception: A possible object cycle was detected in .NET Core 6

51 views Asked by At

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 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company

I get an error in response, because objects contain references to each other.

Is there a way to load data without a cycled relationship?

I use these ways but do not work:

builder.Services.AddControllers().AddJsonOptions(x =>
            x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);

or

builder.Services.AddControllers().AddJsonOptions(x =>
           x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

or

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>
(options => options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

or

builder.Services.AddControllers().AddNewtonsoftJson(x =>

x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

MyError

1

There are 1 answers

0
Qing Guo On

If you're using System.Text.Json, you can configure it like this.

using System.Text.Json.Serialization;

builder.Services
    .AddControllers()
    .AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

You can look Related data and serialization and this answer to know more