© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
11 replies
dev1111

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

I'm working on an API and I have Doctor and Appointment models. The Doctor model has a
List<Appointment>
List<Appointment>
as a prop and Appointment has a Doctor prop too. I understand what's going on but couldn't find a solution for it yet: when I fetch a doctor and
Include(doc => doc.Appointments)
Include(doc => doc.Appointments)
, it seems like, since the Appointment could have a reference to that same Doctor (and it does), they would end up including each other infinitely.

The thing is, if I add a
[JsonIgnore]
[JsonIgnore]
to the Appointment's 'Doctor' property, things start working (since the Doctor won't be present among Appointment's properties) but it won't be serialized when I'm fetching Appointments, even with
Include(appt => appt.Doctor)
Include(appt => appt.Doctor)
. Another odd thing is that Doctor is not added automatically when I fetch an Appointment, but it still complains when
Include(doc => doc.Appointments)
Include(doc => doc.Appointments)
even though I'm not doing
ThenInclude(appt => appt.Doctor)
ThenInclude(appt => appt.Doctor)
right after.

The error code:

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. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.User.
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. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.User.


The
ReferenceHandler.Preserve
ReferenceHandler.Preserve
made it work but it adds $id and $values to the json object and, at first, seemed like a hack (I'm ok with it in case it's not). Any ideas?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

MediatR - System.Text.Json.JsonException: 'S' is an invalid start of a value.
C#CC# / help
2y ago
❔ ✅ System.Text.Json paths
C#CC# / help
3y ago
System.Text.Json Source Generators
C#CC# / help
3y ago
✅ System.Text.Json serialization problem
C#CC# / help
4y ago