Golang omitempty 的用法

原文链接: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}
上一篇:Python基础汇总003--Python面向对象即类(Class)相关的知识点汇总---类的定义、对象的创建和使用、类的属性和方法


下一篇:Linux centos VMware Nginx防盗链、Nginx访问控制、Nginx解析php相关配置、Nginx代理