原文链接:https://blog.csdn.net/skh2015java/article/details/90720692
omitempty作用是在json数据结构转换时,当该字段的值为该字段类型的零值时,忽略该字段。
package main
import (
"fmt"
"encoding/json"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
Grade string `json:"grade,omitempty"`
}
func main() {
stu1 := Student{
Name:"Tom",
Age:18,
Grade:"middle school",
}
stu2 := Student{
Name:"LiLy",
Age:19,
}
stuByts1,_ := json.Marshal(&stu1)
stuByts2 ,_ := json.Marshal(&stu2)
fmt.Println("stu1:",string(stuByts1))
fmt.Println("stu2:",string(stuByts2))
}
打印结果如下:
stu1: {"name":"Tom","age":18,"grade":"middle school"}
stu2: {"name":"LiLy","age":19}