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}
参考