Go的json.Marshal为空对象主因是字段未导出(小写首字母)或存在循环引用;需确保字段大写、用struct tag控制key、排除func/chan等不支持类型,并为time.Time和循环结构显式处理。
Go 的 json.Marshal 只能序列化导出(首字母大写)的结构体字段。如果字段是小写字母开头,比如 name、age,Marshal 后对应字段会直接消失,结果可能是空对象 {} 或缺失关键数据。
常见现象:结构体看起来有值,但输出 JSON 是 {} 或部分字段丢失。
Name、Age
type User struct { Name string `json:"name"` }
json.Marshal 遇到无法表示为 JSON 的类型时会返回错误,典型错误信息是:json: unsupported type: func() 或 json: unsupported type: chan int。
这类问题常出现在误将方法接收器、回调函数或 goroutine 通信结构体直接塞进待序列化对象中。
func、chan、map[interface{}]interface{}、interface{}(且运行时值为不支持类型)interface{} 字段,务必确认其底层值是 JSON 可编码类型(string/number/bool/map/slice/nil)直接 Marshal time.Time 会使用 RFC 3339 格式(如 "2025-05-22T14:30:00Z"),但若结构体字段是未初始化的零值 time.Time{},且没有设置 omitempty,就可能触发 json: invalid use of ,string struct tag, trying to unmarshal unquoted value into time.Time 类似错误(多见于反序列化,但编码时若嵌套在 interface{} 中也可能出问题)。
CreatedAt time.Time `json:"created_at"` 并确保非零值,或用指针 *time.Time 配合 omitempty
MarshalJSON() 方法,返回带引号的字符串字节
time.Time 存进 map[string]interface{} 后再 Marshal —— 它不会自动调用自定义方法Go 的标准库 json 包不检测或处理循环引用。一旦结构体 A 持有 B,B 又持有 A(或通过指针间接形成环),json.Marshal 会无限递归,最终触发栈溢出 panic(runtime: goroutine stack exceeds 1000000000-byte limit)。
这种问题在 ORM 模型(如 GORM 的关联字段)或树形结构中较隐蔽。
*Parent 和 Children []*Node 这类双向引用json.Marshal(struct {
ID int `json:"id"`
Name string `json:"name"`
}{u.ID, u.Name})MarshalJ
SON(),手动控制遍历深度或跳过循环字段
来电咨询