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":{}}
可以發現,沒有給嵌套結構體賦值時,會打印該嵌套結構體的空結構體。這是因爲該空結構體不屬於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}
參考