← 返回 Golang 列表

Go JSON 序列化与结构体标签

encoding/json 的 Marshal/Unmarshal 与 json 标签进阶用法。

结构体标签

type User struct {
  ID    int    `json:"id"`
  Name  string `json:"name,omitempty"`
  Email string `json:"email,omitempty"`
}

序列化与反序列化

data, _ := json.Marshal(user)
json.Unmarshal(data, &user)
提示: omitempty 会在值为零值时省略字段,注意与 nil 区分。