1. 程式人生 > 程式設計 >golang中json的omitempty使用操作

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",Docs:"https://blog.csdn.net/qq_30505673",}

 data2,err := json.Marshal(p2)
 if err != nil {
 panic(err)
 }

 //打印出所有的欄位
 fmt.Printf("%s\n",data2)
}

golang中json的omitempty使用操作

如果沒有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,"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,"price":0}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。