System.Text.Json.JsonException: 检测到可能的对象循环。这可能是由于循环或对象深度大于允许的最大深度 64。考虑在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 来支持循环。
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.
ID: dotnet/serialization-cycle-detected
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| net6.0 | active | — | — | — |
| net7.0 | active | — | — | — |
| net8.0 | active | — | — | — |
| net9.0 | active | — | — | — |
根因分析
JSON 序列化器在序列化过程中遇到了循环引用(例如,父对象引用子对象,子对象又引用父对象),而 System.Text.Json 默认无法处理这种情况。
English
The JSON serializer encountered a circular reference (e.g., a parent referencing a child that references the parent) during serialization, which it cannot handle by default in System.Text.Json.
官方文档
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/preserve-references解决方案
-
Use ReferenceHandler.Preserve in JsonSerializerOptions. Example: 'var options = new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve }; var json = JsonSerializer.Serialize(obj, options);' This adds $id and $ref metadata to handle cycles. -
Apply [JsonIgnore] on the property causing the cycle. For example, if 'Order.Customer' references 'Customer.Orders', add '[JsonIgnore]' on 'Customer.Orders' in the DTO or view model.
-
Use Data Transfer Objects (DTOs) that flatten the object graph and avoid circular references. For example, create 'OrderDto' with 'CustomerId' instead of a full 'Customer' object.
无效尝试
常见但无效的做法:
-
Setting MaxDepth to a very high value (e.g., 1024)
90% 失败
This only increases the depth limit but does not resolve the cycle; the serializer will still throw an exception when it detects the cycle at any depth.
-
Using Newtonsoft.Json instead of System.Text.Json without configuring ReferenceLoopHandling
85% 失败
Newtonsoft.Json also throws an error by default on cycles unless ReferenceLoopHandling.Ignore is set, so simply switching libraries does not fix the issue.
-
Adding [JsonIgnore] on all navigation properties randomly
75% 失败
This may remove necessary data and break API contracts; a targeted approach is needed to identify the specific cycle.