# System.Text.Json.JsonException: 检测到可能的对象循环。这可能是由于循环或对象深度大于允许的最大深度 64。考虑在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 来支持循环。

- **ID:** `dotnet/serialization-cycle-detected`
- **领域:** dotnet
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

JSON 序列化器在序列化过程中遇到了循环引用（例如，父对象引用子对象，子对象又引用父对象），而 System.Text.Json 默认无法处理这种情况。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| net6.0 | active | — | — |
| net7.0 | active | — | — |
| net8.0 | active | — | — |
| net9.0 | active | — | — |

## 解决方案

1. ```
   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.
   ```
2. ```
   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.
   ```
3. ```
   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)** — 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. (90% 失败率)
- **Using Newtonsoft.Json instead of System.Text.Json without configuring ReferenceLoopHandling** — Newtonsoft.Json also throws an error by default on cycles unless ReferenceLoopHandling.Ignore is set, so simply switching libraries does not fix the issue. (85% 失败率)
- **Adding [JsonIgnore] on all navigation properties randomly** — This may remove necessary data and break API contracts; a targeted approach is needed to identify the specific cycle. (75% 失败率)
