dotnet serialization ai_generated true

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 32.

ID: dotnet/serialization-cycle

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
70Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
8 active

Root Cause

JSON serialization cycle errors occur when System.Text.Json encounters circular references in object graphs, commonly from EF Core navigation properties (e.g., Parent -> Children -> Parent). Fix by using ReferenceHandler.IgnoreCycles, DTOs, or [JsonIgnore] attributes.

generic

Workarounds

  1. 90% success Configure ReferenceHandler.IgnoreCycles in JSON serializer options
    In Program.cs: builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; }); This replaces circular references with null during serialization, breaking the cycle without modifying the domain model
  2. 92% success Use DTOs (Data Transfer Objects) to control serialization shape
    Create DTO classes that only contain the properties needed for the API response, without circular navigation properties. Map entities to DTOs before returning: return Ok(entity.Select(e => new EntityDto { Id = e.Id, Name = e.Name })); This gives full control over the serialized shape

Dead Ends

Common approaches that don't work:

  1. Increasing JsonSerializerOptions.MaxDepth to a very high value 95% fail

    A circular reference creates infinite depth; no MaxDepth value will be sufficient. Higher values just delay the exception and waste CPU and memory before the inevitable failure

  2. Removing navigation properties from EF Core entities to prevent cycles 75% fail

    Navigation properties are essential for EF Core's relationship mapping, Include operations, and lazy loading. Removing them breaks queries and forces manual joins, degrading the ORM experience significantly

Error Chain

Leads to:
Preceded by:
Frequently confused with: