一句話總結:帶有omitempty字段的成員,若是該字段爲nil(字符串」「,空數組等),則打包的JSON結果不會有這個字段。json
咱們把proto文件自動生成go代碼時會出現omitempty字段,以下數組
type Reply struct { Code uint32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` CodeMsg string `protobuf:"bytes,2,opt,name=codeMsg" json:"codeMsg,omitempty"` }
直接上代碼ui
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Addr string `json:"addr,omitempty"` } func main() { p1 := Person{ Name: "simon", Age: 22, } data, err := json.Marshal(p1) if err != nil { panic(err) } // p1 沒有爲Addr賦值,這裏打印出來不會出現Addr的字段 fmt.Printf("%s\n", data) p2 := Person{ Name: "simon", Age: 22, Addr: "China", } data2, err := json.Marshal(p2) if err != nil { panic(err) } // p2 則會打印全部 fmt.Printf("%s\n", data2) }
{"name":"simon","age":22} {"name":"simon","age":22,"addr":"China"} Process finished with exit code 0