脚本宝典收集整理的这篇文章主要介绍了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":{}}
可以发现,没有给嵌套结构体赋值时,会打印该嵌套结构体的空结构体。这是因为该空结构体不属于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}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本宝典。如有错误或未考虑完全的地方,望不吝赐教。
以上是脚本宝典为你收集整理的golang中json的omitempty使用操作全部内容,希望文章能够帮你解决golang中json的omitempty使用操作所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。