实现说明
JSON Marshal 的引用环检测可以归结为函数 main。
使用要点
- 演示输出是带标签的(
cycle error:、flat json:),每个操作都会留下自己的一行标注。
常见问题
运行「JSON Marshal 的引用环检测」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 cycle error:、flat json: 标签标明各步骤。
核心语句
b.Next = a // cycle: a direct Marshal would recurse forever; encoding/json detects it mid-traversal and returns an error
代码示例
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Node struct {
Name string
Next *Node
}
func main() {
a := &Node{Name: "head"}
b := &Node{Name: "tail"}
a.Next = b
b.Next = a // cycle: a direct Marshal would recurse forever; encoding/json detects it mid-traversal and returns an error
_, err := json.Marshal(a)
fmt.Println("cycle error:", err != nil, strings.Contains(err.Error(), "cycle"))
// fix: flatten the graph into an acyclic DTO, then serialize
flat := struct {
Name string `json:"name"`
Next string `json:"next"`
}{Name: a.Name, Next: a.Next.Name}
out, err := json.Marshal(flat)
fmt.Println("flat json:", string(out), "err:", err)
}