# json：无效的递归类型：类型 MyStruct 具有递归 JSON 方法

- **ID:** `go/json-marshal-infinite-recursion`
- **领域:** go
- **类别:** encoding_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

类型上的自定义 MarshalJSON 或 UnmarshalJSON 方法对自身调用 json.Marshal 或 json.Unmarshal，导致无限递归。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Go 1.15 | active | — | — |
| Go 1.16 | active | — | — |
| Go 1.17 | active | — | — |
| Go 1.18 | active | — | — |
| Go 1.19 | active | — | — |
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |
| Go 1.23 | active | — | — |

## 解决方案

1. ```
   Define an alias type (type MyStructAlias MyStruct) and marshal the alias instead of the original type
   ```
2. ```
   Use a raw byte slice or map[string]interface{} for manual marshaling without calling json.Marshal on self
   ```
3. ```
   Implement MarshalJSON by calling json.Marshal on a temporary struct that mirrors the fields without the recursive method
   ```

## 无效尝试

- **** — Both functions call the same MarshalJSON method; recursion persists. (95% 失败率)
- **** — Loses custom serialization behavior; data may be serialized incorrectly. (70% 失败率)
- **** — json package detects recursion before runtime depth limit; counter doesn't prevent detection. (80% 失败率)
