golang中json的omitempty使用操作
我就廢話不多說了,大家還是直接看代碼吧~
package main import ( "encoding/json" "fmt" ) type Project struct { Name string `json:"name"` Url string `json:"url"` Docs string `json:"docs,omitempty"` } func main() { p1 := Project{ Name:"hello name", Url:"https://blog.csdn.net/qq_30505673", } data, err := json.Marshal(p1) if err != nil { panic(err) } // Docs定義為omitempty所以不會出現Docs的字段 fmt.Printf("%s\n", data) p2 := Project{ Name:"lovego", Url:"https://blog.csdn.net/qq_30505673", Docs:"https://blog.csdn.net/qq_30505673", } data2, err := json.Marshal(p2) if err != nil { panic(err) } //打印出所有的字段 fmt.Printf("%s\n", data2) }
如果沒有omitempty,該字段是會顯示的。
補充:golang omitempty實現嵌套結構體的省略輸出
golang在處理json轉換時,對于標簽omitempty定義的field,如果給它賦得值恰好等于空值(比如:false、0、""、nil指針、nil接口、長度為0的數組、切片、映射),則在轉為json之后不會輸出這個field。
那么,針對結構體中嵌套結構體,如果嵌套結構體為空,是否也會忽略?如果要忽略空結構體輸出,怎么處理?
情況一:匿名結構體:使用omitempty修飾該匿名結構體中的字段,那么當為空時不會輸出
type Book struct{ Name string `json:"name"` Price float32 `json:"price"` Desc string `json:"desc,omitempty"` Author //匿名結構體 } type Author struct { Gender int `json:"gender,omitempty"` Age int `json:"age,omitempty"` } func main() { var book Book book.Name = "testBook" bookByte,_:=json.Marshal(book) fmt.Printf("%s\n", string(bookByte)) }
輸出:
{"name":"testBook","price":0}
情況二:非匿名結構體
type Book struct{ Name string `json:"name"` Price float32 `json:"price"` Desc string `json:"desc,omitempty"` Author Author `json:"author,omitempty"` } type Author struct { Gender int `json:"gender,omitempty"` Age int `json:"age,omitempty"` } func main() { var book Book book.Name = "testBook" bookByte,_:=json.Marshal(book) fmt.Printf("%s\n", string(bookByte)) }
輸出:
{"name":"testBook","price":0,"author":{}}
可以發(fā)現,沒有給嵌套結構體賦值時,會打印該嵌套結構體的空結構體。這是因為該空結構體不屬于omitempty能識別的空值(false、0、""、nil指針、nil接口、長度為0的數組、切片、映射)。但若期望該嵌套結構體的空結構體也不會輸出,可以通過指針實現。
type Book struct{ Name string `json:"name"` Price float32 `json:"price"` Desc string `json:"desc,omitempty"` Author *Author `json:"author,omitempty"` } type Author struct { Gender int `json:"gender"` Age int `json:"age"` } func main() { var book Book book.Name = "testBook" bookByte,_:=json.Marshal(book) fmt.Printf("%s\n", string(bookByte)) }
輸出:
{"name":"testBook","price":0}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。