dotnet serialization_error 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 64.

ID: dotnet/aspnetcore-json-cycle

Also available as: JSON · Markdown · 中文
90%Fix Rate
86%Confidence
1Evidence
2023-07-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
dotnet 6.0 active
dotnet 8.0 active
System.Text.Json 6.0 active
System.Text.Json 8.0 active

Root Cause

JsonSerializer encounters a circular reference in the object graph (e.g., navigation properties referencing each other) or the nesting depth exceeds the default limit.

generic

中文

JsonSerializer 在对象图中遇到循环引用(例如导航属性相互引用)或嵌套深度超过默认限制。

Official Documentation

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/preserve-references

Workarounds

  1. 90% success Configure System.Text.Json to handle reference loops using ReferenceHandler.Preserve. Example in Program.cs.
    Configure System.Text.Json to handle reference loops using ReferenceHandler.Preserve. Example in Program.cs.
  2. 85% success Use DTOs or view models that flatten the object graph, avoiding circular references.
    Use DTOs or view models that flatten the object graph, avoiding circular references.
  3. 80% success Set ReferenceHandler.IgnoreCycles to ignore navigation properties that cause cycles.
    Set ReferenceHandler.IgnoreCycles to ignore navigation properties that cause cycles.

中文步骤

  1. Configure System.Text.Json to handle reference loops using ReferenceHandler.Preserve. Example in Program.cs.
  2. Use DTOs or view models that flatten the object graph, avoiding circular references.
  3. Set ReferenceHandler.IgnoreCycles to ignore navigation properties that cause cycles.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Does not break the cycle; serializer will still fail with stack overflow or infinite loop.

  2. 70% fail

    May hide needed data; can break client-side functionality if important relationships are omitted.

  3. 80% fail

    Newtonsoft.Json also has a default reference loop handling that throws; needs explicit configuration.