← 中文资源

简体中文版本

JSON 指针字段区分缺省

可空字段用指针类型承接:缺失或显式 null 都解成 nil,与空串、0 等零值区分开;配合 omitempty,nil 指针在 Marshal 时整体省略,未加 omitempty 的字段输出 null。

阅读英文原文

实现说明

全部逻辑都在函数 describe、main中。 重复被限制在 for _, raw := range payloads 里——其余代码按顺序各跑一遍。没有静默穿透——中途有 1 个检查点测试 err != nil。

使用要点

  • 跑完文件,输出里会留下标记——bad payload:。
  • main 的演示流程是 describe——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「JSON 指针字段区分缺省」会打印什么?

运行文件本身,bad payload: 这些前缀各对应一段演示逻辑。

主要签名是 func describe(p Profile) string

核心语句

return fmt.Sprintf("name=%s bio=%s age=%d", p.Name, bio, *p.Age)
return fmt.Sprintf("name=%s bio=%s age=unset", p.Name, bio)
for _, raw := range payloads {
	var p Profile
	if err := json.Unmarshal([]byte(raw), &p); err != nil {
		fmt.Println("bad payload:", err)
		continue
	}
	fmt.Println(describe(p))
}

代码示例

package main

import (
	"encoding/json"
	"fmt"
)

type Profile struct {
	Name string  `json:"name"`
	Bio  *string `json:"bio"`           // 缺失或显式 null 都解成 nil
	Age  *int    `json:"age,omitempty"` // nil 在 Marshal 时整个字段省略
}

func describe(p Profile) string {
	bio := "unset"
	if p.Bio != nil {
		bio = fmt.Sprintf("%q", *p.Bio)
	}
	if p.Age != nil {
		return fmt.Sprintf("name=%s bio=%s age=%d", p.Name, bio, *p.Age)
	}
	return fmt.Sprintf("name=%s bio=%s age=unset", p.Name, bio)
}

func main() {
	payloads := []string{
		`{"name":"ada","bio":"builder","age":30}`,
		`{"name":"ada","bio":""}`,
		`{"name":"ada"}`,
	}
	for _, raw := range payloads {
		var p Profile
		if err := json.Unmarshal([]byte(raw), &p); err != nil {
			fmt.Println("bad payload:", err)
			continue
		}
		fmt.Println(describe(p))
	}

	// 未加 omitempty 的 nil 指针输出 null;加了 omitempty 的直接省略
	out, _ := json.Marshal(Profile{Name: "ada"})
	fmt.Println(string(out))
}