问题
在网络通信时,往往将结构体转换为json发送,在一些复杂的结构体中,往往存在嵌套结构,此时在嵌套结构中使用了omitempty是不生效的(如果不是指针类型的话),从而造成json转换失败,请求不到数据。
omitempty
对于基本类型
- 不使用omitempty,转换时会有默认值
package main
import (
"encoding/json"
"fmt"
)
type Dog struct {
Breed string
WeightKg int
}
func main() {
d := Dog{
Breed: "pug",
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{"Breed":"pug","WeightKg":0}
- 使用omitempty,转换时会忽略该字段
package main
import (
"encoding/json"
"fmt"
)
type Dog struct {
Breed string
WeightKg int `json:",omitempty"`
}
func main() {
d := Dog{
Breed: "pug",
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{"Breed":"pug"}
- 使用omitempty且值为0或""或nil,此时即使赋值这些也会忽略该字段,此时可以使用指针
package main
import (
"encoding/json"
"fmt"
)
type Restaurant struct {
NumberOfCustomers int`json:",omitempty"`
}
func main() {
d := Restaurant{
NumberOfCustomers: 0,
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{}
package main
import (
"encoding/json"
"fmt"
)
type Restaurant struct {
NumberOfCustomers *int `json:",omitempty"`
}
func main() {
n := 0
d := Restaurant{
NumberOfCustomers: &n,
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{"NumberOfCustomers":0}
对于嵌套结构体
使用omitempty而不使用指针类型,并不能省略,而是生成默认值
package main
import (
"encoding/json"
"fmt"
)
type dimension struct {
Height int
Width int
}
type Dog struct {
Breed string
WeightKg int
Size dimension `json:",omitempty"`
}
func main() {
d := Dog{
Breed: "pug",
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{"Breed":"pug","WeightKg":0,"Size":{"Height":0,"Width":0}}
使用omitempty而使用指针类型,可以被省略
package main
import (
"encoding/json"
"fmt"
)
type dimension struct {
Height int
Width int
}
type Dog struct {
Breed string
WeightKg int
Size *dimension `json:",omitempty"`
}
func main() {
d := Dog{
Breed: "pug",
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
输出
{"Breed":"pug","WeightKg":0}