您现在的位置是:网站首页> 编程资料编程资料

golang中json的omitempty使用操作_Golang_

2023-05-26 391人已围观

简介 golang中json的omitempty使用操作_Golang_

我就废话不多说了,大家还是直接看代码吧~

 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":{}}

可以发现,没有给嵌套结构体赋值时,会打印该嵌套结构体的空结构体。这是因为该空结构体不属于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}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

-六神源码网