【发布时间】:2022-01-22 13:32:25
【问题描述】:
我对内联使用了相同的结构,并使用 omitempty 标记嵌套在主结构中。由于我没有在键中分配任何值,因此我在 JSON 中得到了空结构。在这种情况下有人可以帮助我吗?
package main
import (
"encoding/json"
"fmt"
)
type Customer struct {
Name string `json:"name,omitempty" bson:"name"`
Gender string `json:"gender,omitempty" bson:"gender"`
Address `json:",inline" bson:",inline" `
OptionalAddresses []Address `json:"optionalAddresses,omitempty" bson:"optionalAddresses"`
}
type Address struct {
Country string `json:"country,omitempty" bson:"country"`
ZoneDetail Zone `json:"zone,omitempty" bson:"zone"`
}
type Zone struct {
Latitude float64 `json:"lat,omitempty" bson:"lat,omitempty"`
Longitude float64 `json:"lon,omitempty" bson:"lon,omitempty"`
}
func main() {
cust := Customer{Name: "abc", Gender: "M"}
dataByt, _ := json.Marshal(cust)
fmt.Println(string(dataByt))
}
输出:
{"name":"abc","gender":"M","zone":{}}
【问题讨论】:
-
您能否将您期望的输出添加到您的问题中?
-
空结构体依然存在,使用指针代替:
ZoneDetail *Zone -
按文档工作。有什么问题?
标签: json go marshalling