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"` //这里加上指针类型,但是后面给这个这个指针元素赋值的时候需要(*Author).Age = xxx
}
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}
实际开发过程中,我使用的是第二种场景,因为给前端API返回的数据,经常会有嵌套的情况,但是这个 Author 需要先初始化,不然会报错 nil pointer
