← 中文资源

简体中文版本

JSON Marshal 的引用环检测

encoding/json 在序列化时检测引用环:Next 指回自己时返回 unsupported value 错误;把图压平成无环 DTO 再序列化即可正常输出。

阅读英文原文

实现说明

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)
}