go encoding_error ai_generated true

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

json: invalid recursive type: type MyStruct has recursive JSON method

ID: go/json-marshal-infinite-recursion

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2023-07-12首次发现

版本兼容性

版本状态引入弃用备注
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

根因分析

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

English

A custom MarshalJSON or UnmarshalJSON method on a type calls json.Marshal or json.Unmarshal on itself, causing infinite recursion.

generic

官方文档

https://pkg.go.dev/encoding/json#Marshaler

解决方案

  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

无效尝试

常见但无效的做法:

  1. 95% 失败

    Both functions call the same MarshalJSON method; recursion persists.

  2. 70% 失败

    Loses custom serialization behavior; data may be serialized incorrectly.

  3. 80% 失败

    json package detects recursion before runtime depth limit; counter doesn't prevent detection.