omitempty
标签的作用:
序列化成JSON时,当该字段的值为该字段类型的零值时,忽略该字段。
type Student struct {
Id int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Age float64 `json:"age,omitempty"`
B bool `json:"b,omitempty"`
Id1 *int `json:"id1,omitempty"`
Name1 *string `json:"name1,omitempty"`
Age1 *float64 `json:"age1,omitempty"`
B1 *bool `json:"b1,omitempty"`
}
func main() {
s1 := Student{
Id: 1,
Name: "张三",
}
data1, _ := json.Marshal(s1)
fmt.Printf("%s\n", data1)
emptys := ""
emptyI := 0
emptyf := 0.0
emptyB := false
s2 := Student{
Name: "",
Id: 0,
Age: 0.0,
B: false,
Name1: &emptys,
Id1: &emptyI,
Age1: &emptyf,
B1: &emptyB,
}
data2, _ := json.Marshal(s2)
fmt.Printf("%s\n", data2)
}
输出结果:
{"id":1,"name":"张三"}
{"id1":0,"name1":"","age1":0,"b1":false}
可以看到string
、int
、float64
、bool
类型的零值都被忽略了。
那如果 非要传 数据类型对应的零值 咋办呢?
答:使用指针类型。根据上面的运行结果,可以看到使用指针类型(*string
、*int
、*float64
、*bool
),可以传对应的数据类型的零值。