Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

System.Text.Json: A possible object cycle was detected

Serialization hit a cycle or the depth limit: EF navigation properties point both ways. Project a DTO, use IgnoreCycles, or Preserve references.

~4 min readC#
#C##.NET#System.Text.Json#Debugging
A C# object graph crate looping into itself at a cyan serializer gate, an amber DTO card beside it

Introduction & Quick Summary

text
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. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.orders[0].customer.orders[0].customer.orders ...

System.Text.Json refuses to serialize an object graph it cannot finish. A cycle — parent pointing at child, child pointing back at parent — would produce infinite JSON, so the serializer stops at 64 levels and throws. EF Core navigation properties create exactly this shape by default.

Four fixes, from best to last resort:

  • Project to a DTO. Serialize a shape that has no back-references. This also fixes over-posting and oversized payloads.
  • ReferenceHandler.IgnoreCycles. The serializer writes null where the cycle would repeat, so the JSON stays finite and deserializes without metadata.
  • ReferenceHandler.Preserve. Emits $id and $ref entries so the graph round-trips. Only use it when the client understands that contract.
  • [JsonIgnore] on the back-pointer. Keeps the graph intact for code, removes one direction for JSON.

If the graph is genuinely deep rather than cyclic, the depth limit is the problem and MaxDepth is the setting — but a 64-level business object usually means an accidental recursion, not a legitimate one.

ApproachOutput shapeRound-trips graphClient impact
DTO projectionFlat, explicitNoClean, stable contract
IgnoreCyclesCycle becomes nullNoMay see unexpected nulls
Preserve$id / $refYesRequires matching serializer
[JsonIgnore]One direction removedNoSmaller payload
MaxDepth raisedFull repetitionNoHuge payloads, still finite

Core Mechanics, Signatures & Reproducible Setup

JsonSerializer walks the object graph depth-first and tracks how deep it currently is. When depth exceeds MaxDepth (64 by default) it throws JsonException with the cycle hint, because the two conditions are indistinguishable from the writer's perspective without reference tracking.

Reproduction with plain classes:

csharp
public class Customer { public int Id { get; set; } public string Name { get; set; } = ""; public List<Order> Orders { get; set; } = new(); } public class Order { public int Id { get; set; } public Customer Customer { get; set; } = null!; public List<OrderLine> Lines { get; set; } = new(); } public class OrderLine { public int Id { get; set; } public Order Order { get; set; } = null!; public int Quantity { get; set; } }
csharp
var customer = new Customer { Id = 1, Name = "Ada" }; var order = new Order { Id = 10, Customer = customer }; customer.Orders.Add(order); order.Lines.Add(new OrderLine { Id = 100, Order = order, Quantity = 2 }); var json = JsonSerializer.Serialize(customer); // JsonException: A possible object cycle was detected.

EF Core produces the same structure from Include calls, because navigation fixup sets both sides of every relationship.

The minimal options-based fix:

csharp
var options = new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.IgnoreCycles, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, WriteIndented = false }; var json = JsonSerializer.Serialize(customer, options);

IgnoreCycles replaces the repeated reference with null; WhenWritingNull then drops those properties, which keeps the payload readable.

Key Comparison Table

OptionWhere to setApplies to
ReferenceHandler.IgnoreCyclesJsonSerializerOptionsJsonSerializer, MVC, minimal APIs
ReferenceHandler.PreserveJsonSerializerOptionsRequires Preserve on read
MaxDepthJsonSerializerOptionsAny graph, cycle or not
[JsonIgnore]Property or fieldAll serialization of that type
DTO / projectionQuery or mapping layerPreferred for APIs
ReferenceLoopHandling.IgnoreNewtonsoft.Json settingsNewtonsoft only
SerializerDefault cycle behaviorFix
System.Text.Json (ASP.NET Core 3.0+)ThrowsHandler or DTO
Newtonsoft.Json (ASP.NET Core 2.x default)Serializes until stack limitReferenceLoopHandling.Ignore
JsonSerializer with source generationSame as reflection pathHandler supported

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: Project before serializing

csharp
[HttpGet("customers/{id:int}")] public async Task<ActionResult<CustomerDto>> Get(int id) { var customer = await db.Customers .Include(c => c.Orders) .ThenInclude(o => o.Lines) .AsNoTracking() .FirstOrDefaultAsync(c => c.Id == id); if (customer is null) return NotFound(); return new CustomerDto( customer.Id, customer.Name, customer.Orders.Select(o => new OrderDto( o.Id, o.Lines.Select(l => new LineDto(l.Id, l.Quantity)).ToList() )).ToList()); }
csharp
public record LineDto(int Id, int Quantity); public record OrderDto(int Id, List<LineDto> Lines); public record CustomerDto(int Id, string Name, List<OrderDto> Orders);

The DTO has no reference to its parent, so no cycle exists. It also stops the API from silently exposing new entity properties added later — a serializer setting cannot do that.

Case 2: IgnoreCycles and the null it writes

csharp
builder.Services.ConfigureHttpJsonOptions(o => { o.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; });

For minimal APIs, ConfigureHttpJsonOptions is the hook; AddControllers().AddJsonOptions(...) only affects MVC. Setting one and testing the other is a common reason "the fix did nothing".

With IgnoreCycles, the second occurrence of a reference becomes null — not omitted unless WhenWritingNull is set, and not merged. A client that expects customer.orders[0].customer.name gets null there. That may be acceptable for a detail endpoint and unacceptable for an export.

Case 3: Preserve changes the contract

csharp
o.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
{ "$id": "1", "Id": 1, "Name": "Ada", "Orders": { "$id": "2", "$values": [ { "$id": "3", "Id": 10, "Customer": { "$ref": "2" }, "Lines": { "$values": [] } } ] } }

Every object becomes an $id-tagged node and arrays gain a $values wrapper.

Case 4: [JsonIgnore] on one side

csharp
public class Order { public int Id { get; set; } public List<OrderLine> Lines { get; set; } = new(); [JsonIgnore] public Customer Customer { get; set; } = null!; }

This removes the back-pointer from every serialization of Order, including nested ones, and does not affect EF Core mapping. It is the cheapest fix when the entity must be serialized directly, and it fails quietly if a client needs that field — a serializer-level decision embedded in a domain model.

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] does not help: the back-pointer is not null, it points at a live object.

Case 5: Depth, not a cycle

csharp
public class Node { public string Name { get; set; } = ""; public List<Node> Children { get; set; } = new(); }

A 70-deep category tree trips the same exception with a legitimate structure. Raising the limit is correct here:

csharp
var options = new JsonSerializerOptions { MaxDepth = 128 };

Raise it deliberately and keep serialization bounded.

Case 6: The Newtonsoft escape hatch does not exist here

csharp
// Newtonsoft JsonConvert.SerializeObject(value, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

Projects migrating from Newtonsoft often copy the setting and expect the same behavior from System.Text.Json, which has no ReferenceLoopHandling. The nearest equivalents are ReferenceHandler.IgnoreCycles (write null) and Preserve (write $ref); Newtonsoft's Ignore silently omits the property instead of writing null, which is why payloads can change shape during the migration.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Setting options on the wrong serializer. JsonUtils.Options used directly, AddJsonOptions applied to a minimal API, or JsonSerializerOptions.Default mutated at runtime — all leave the HTTP pipeline on its own defaults.
  • IgnoreCycles without WhenWritingNull. The payload grows with "customer": null entries that clients must tolerate.
  • Preserve on one side only. A service that writes $id and a consumer that reads a normal DTO get nulls or deserialization errors with no obvious cause.
  • AsNoTracking does not remove fixup. The entities still reference each other; tracking only changes whether changes are saved.
  • Source-generated contexts. JsonSerializerContext supports ReferenceHandler, but options must be attached to the context, not passed per call.
  • Entity Framework lazy loading proxies. Lazy loading can create cycles that do not exist in the mapped model; Include/projection removes the surprise.
  • .NET version drift. Cycle messages and Path: detail differ between .NET 6 and 8/9, and Path is the fastest way to find the offending navigation property.

Paste a failing payload into the JSON formatter to see how deep the repetition goes before it becomes null, and use the diff tool to compare a working DTO response with the entity response that broke — the extra back-reference is usually one line.

Primary references: Preserve references in System.Text.Json documents ReferenceHandler.IgnoreCycles and Preserve, and the System.Text.Json overview covers MaxDepth, options and source generation.

Official references

primary documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.